package com.ztc.ZtcClasses.web;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aqgj.Attachment.bean.Attachment;
import com.aqgj.User.bean.User;
import com.ztc.ZtcCar.bean.ZtcCar;
import com.ztc.ZtcCar.service.ZtcCarManager;
import com.ztc.ZtcClasses.bean.ZtcClasses;
import com.ztc.ZtcClasses.dao.ZtcClassesDao;
import com.ztc.ZtcClasses.service.ZtcClassesManager;
import com.ztc.ZtcClassesForSale.bean.ZtcClassesForSale;
import com.ztc.ZtcClassesForSale.service.ZtcClassesForSaleManager;
import com.ztc.ZtcClassesPrice.bean.ZtcClassesPrice;
import com.ztc.ZtcClassesPrice.dao.ZtcClassesPriceDao;
import com.ztc.ZtcClassesPrice.service.ZtcClassesPriceManager;
import com.ztc.ZtcClassesPriceForSale.bean.ZtcClassesPriceForSale;
import com.ztc.ZtcClassesPriceForSale.service.ZtcClassesPriceForSaleManager;
import com.ztc.ZtcClassesSite.bean.ZtcClassesSite;
import com.ztc.ZtcClassesSite.service.ZtcClassesSiteManager;
import com.ztc.ZtcClassesSiteForSale.bean.ZtcClassesSiteForSale;
import com.ztc.ZtcClassesSiteForSale.service.ZtcClassesSiteForSaleManager;
import com.ztc.ZtcDriver.bean.ZtcDriver;
import com.ztc.ZtcDriver.service.ZtcDriverManager;
import com.ztc.ZtcOrder.bean.ZtcOrder;
import com.ztc.ZtcOrder.service.ZtcOrderManager;
import com.ztc.ZtcOrderTicket.bean.ZtcOrderTicket;
import com.ztc.ZtcOrderTicket.service.ZtcOrderTicketManager;
import com.ztc.ZtcRoute.bean.ZtcRoute;
import com.ztc.ZtcRoute.service.ZtcRouteManager;
import com.ztc.ZtcRouteAttachment.bean.ZtcRouteAttachment;
import com.ztc.ZtcTransport.bean.ZtcTransport;
import com.ztc.ZtcTransport.service.ZtcTransportManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("ztc_classes_action")
public class ZtcClassesAction {
	@Autowired
	private ZtcClassesManager ztcClassesManager;
	@Autowired
	private ZtcRouteManager ztcRouteManager;
	@Autowired
	private ZtcClassesSiteManager ztcClassesSiteManager;
	@Autowired
	private ZtcClassesPriceManager ztcClassesPriceManager;
	@Autowired
	private ZtcClassesPriceDao ztcClassesPriceDao;
	@Autowired
	private ZtcClassesDao ztcClassesDao;
	@Autowired
	private ZtcClassesForSaleManager ztcClassesForSaleManager;
	@Autowired
	private ZtcClassesSiteForSaleManager ztcClassesSiteForSaleManager;
	@Autowired
	private ZtcClassesPriceForSaleManager ztcClassesPriceForSaleManager;
	@Autowired
	private ZtcOrderManager orderManager;
	@Autowired
	private ZtcTransportManager ztcTransportManager;
	@Autowired
	private ZtcOrderTicketManager orderTicketManager;
	@Autowired
	private ZtcDriverManager ztcDriverManager;
	@Autowired
	private ZtcCarManager ztcCarManager;
	private static final Logger log = LogManager.getLogger(ZtcClasses.class);
	private static final SimpleDateFormat DATE_FORMET = new SimpleDateFormat("yyyy-MM-dd");
	private static final SimpleDateFormat DATE_TIME_FORMET = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	private static final SimpleDateFormat TIME_FORMET = new SimpleDateFormat("HH:mm");
	private static final int autoArangeClassesForSaleDays = 34;
	private static final float childSeatRatio = 0.1f;

	/**
	 * 添加班次模板并自动或手动添加在线班次
	 * @param routeId 线路id
	 * @param name 名称
	 * @param carType 车型
	 * @param carId 车辆id
	 * @param driverId 司机id
	 * @param seatNumber 总座数
	 * @param childSeatNumber 儿童座数
	 * @param departureDate 发车日期
	 * @param isRefund 是否可退票
	 * @param fsTimerbDeparture 发车前多长时间停止售票
	 * @param data 梯形表数据
	 * @param remark 备注
	 * @param departureType 发车类型：1.自动排班2.选择日期排班
	 * @param dayFrequencyType 发车频率按天
	 * @param weekAllDays 发车频率按周
	 * @param monthAllDays 发车频率按月
	 * @param preSaleDays 预售天数
	 * @param selectDepartureDates 选择的日期集合
	 * @param session
	 * @return 操作结果信息
	 * @throws ParseException
	 */
	@RequestMapping("sign")
	@ResponseBody
	public HashMap<String, Object> save(String routeId, String name, String carType, String carId, String driverId,
										String seatNumber, String childSeatNumber, String departureDate, String isRefund, String fsTimerbDeparture,
										String data, String remark, String departureType, String dayFrequencyType, String weekAllDays,
										String monthAllDays, String preSaleDays, String selectDepartureDates,String autoArrangeEndDate, HttpSession session)
			throws ParseException {
		log.info("开始添加");
		Date now = new Date();
		HashMap<String, Object> wapper = new HashMap<>();
//		ZtcRoute ztcRoute = new ZtcRoute();
//		ztcRoute.setId(routeId);
//		ZtcRoute ztcRouteBean = ztcRouteManager.searchInfoEquals(ztcRoute).get(0);
		ZtcRoute ztcRouteBean=ztcRouteManager.getById(routeId);
		if(ztcRouteBean==null){
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "获取模板失败！");
			log.info("获取模板失败！");
			return wapper;
		}
		User user = (User) session.getAttribute("userInfo");
		if (user == null || "".equals(user)) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "用户未登录");
			log.info("用户未登录");
			return wapper;
		}
		ZtcTransport transport = ztcTransportManager.get(user.getTransportId());
		int transportType = transport.getType();
		if (transportType == 0 || transportType == 1 || transportType == 2) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "非运营公司或车方不可操作班次");
			log.info("非运营公司或车方不可操作班次");
			return wapper;
		}
		if (transport.getStatus() == 4) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "该用户公司已被冻结，不可发布班次");
			log.info("该用户公司已被冻结，不可发布班次");
			return wapper;
		}
		LinkedHashMap<String, String> argumentsAndRoles = new LinkedHashMap<>();
		if ("".equals(carId) || carId == null) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "请选择车辆");
			return wapper;
		}
		if ("".equals(driverId) || driverId == null) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "请选择司机");
			return wapper;
		}
		if ("".equals(fsTimerbDeparture) || fsTimerbDeparture == null) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "请填写发车前暂停售票的时间范围");
			return wapper;
		}
		argumentsAndRoles.put(fsTimerbDeparture + "#发车前暂停售票的时间范围格式如'1.01'",
				"^(([1-9][0-9]{0,9})|([0])|(([0-9].[0-9]{1,2})|([1-9][0-9]{1,7}.[0-9]{1})|([1-9][0-9]{1,6}.[0-9]{2})))$");
		if ("".equals(seatNumber) || seatNumber == null) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "请填写总座数");
			return wapper;
		}
		argumentsAndRoles.put(seatNumber + "#总票格式如'9'或'12'最小1最大不超过65", "^(([1-9])|([1-5][0-9])|([6][0-5]))$");
		if ("".equals(childSeatNumber) || childSeatNumber == null) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "请填写儿童座数");
			return wapper;
		}
		argumentsAndRoles.put(childSeatNumber + "#儿童票格式如'0'最大不超过6", "^[0-6]$");
		if ("".equals(departureDate) || departureDate == null) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "请填写发车日期");
			return wapper;
		}
		argumentsAndRoles.put(departureDate + "#发车日期格式如'2017-12-26'必须大于等于当前日期",
				"^[2][0-9]{3}-(([0][1-9])|([1][0-2]))-(([1-2][0-9])|([0][1-9])|([3][0-1]))$");
		if ("".equals(preSaleDays) || preSaleDays == null) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "请填写预售期");
			return wapper;
		}
		argumentsAndRoles.put(preSaleDays + "#预售期格式如'1'必须大于等于1", "^(([1-9])|([1-9][0-9]+))$");
		examineArgument(argumentsAndRoles, wapper);
		if ("false".equals(String.valueOf(wapper.get("success")))) {
			return wapper;
		}
		JSONArray dataArray = JSON.parseArray(data);
		JSONArray siteArray = new JSONArray();
		JSONArray priceArray = new JSONArray();
		getSiteAndPriceArray(dataArray, siteArray, priceArray);
		for (int i = 0; i < siteArray.size(); i++) {
			JSONObject object = siteArray.getJSONObject(i);
			//验证站点
			examineSiteInfo(departureDate, wapper, siteArray, i, object);
			if ("false".equals(String.valueOf(wapper.get("success")))) {
				return wapper;
			}
		}
		examinePriceInfo(priceArray, wapper);
		if ("false".equals(String.valueOf(wapper.get("success")))) {
			return wapper;
		}
		if (weekAllDays != null && !"".equals(weekAllDays)) {
			weekAllDays = weekAllDays.substring(1, weekAllDays.length() - 1);
			weekAllDays = weekAllDays.replace("\"", "");
		}
		if (monthAllDays != null && !"".equals(monthAllDays)) {
			monthAllDays = monthAllDays.substring(1, monthAllDays.length() - 1);
			monthAllDays = monthAllDays.replace("\"", "");
		}
		// 构建班次
		ZtcClasses ztcClasses = getZtcClasses(name, user == null ? "" : user.getId(), carType, carId, driverId, routeId,
				remark, isRefund, departureDate, preSaleDays, departureType, fsTimerbDeparture, dayFrequencyType,
				weekAllDays, monthAllDays, now);
		String ztcClassesId = saveClassesInfo(seatNumber, childSeatNumber, departureDate, ztcRouteBean, wapper,
				siteArray, priceArray, ztcClasses);
		if ("false".equals(String.valueOf(wapper.get("success")))) {
			return wapper;
		}
		// 构建在售班次
		List<Date> departureAllDates = new ArrayList<>();
		//自动排班
		if ("1".equals(departureType)) {
			departureAllDates = generateDepartureDatesOnAutoArrange(departureDate, dayFrequencyType, weekAllDays,
					monthAllDays,autoArrangeEndDate);
			if ("false".equals(String.valueOf(wapper.get("success")))) {
				return wapper;
			}
		} else {
			departureAllDates.add(DATE_TIME_FORMET.parse(departureDate + " " + "00:00:00"));
			if (!"[]".equals(selectDepartureDates) && selectDepartureDates != null) {
				selectDepartureDates = selectDepartureDates.substring(1, selectDepartureDates.length() - 1);
				String[] departureDates = selectDepartureDates.split(",");
				for (int i = 0; i < departureDates.length; i++) {
					String selectDepartureDate = departureDates[i];
					selectDepartureDate = selectDepartureDate.substring(1, selectDepartureDate.length() - 1);
					Date date = DATE_TIME_FORMET.parse(selectDepartureDate + " " + "00:00:00");
					if (!departureAllDates.contains(date)) {
						departureAllDates.add(date);
					}
				}
			} else {
				wapper.put("success", Boolean.valueOf(false));
				wapper.put("msg", "定时发班请选择日期");
				log.info("定时发班请选择日期");
				return wapper;
			}
		}
		getSiteAndPriceWithSeatInfoArray(dataArray, siteArray, priceArray, seatNumber);
		String result=ztcClassesDao.batchInsert(departureAllDates, name, user, carType, carId,
				driverId, ztcClassesId, remark, isRefund,fsTimerbDeparture, seatNumber, childSeatNumber, ztcRouteBean.getFkZtcTransportId(), siteArray,
				priceArray);
		if(!"1".equals(result)){
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "网络错误");
			log.info("网络错误");
			return wapper;
		}
		String stringList = findListByClasses(ztcClassesId);
		JSONArray jsonList = JSON.parseArray(stringList);
		wapper.put("list", jsonList);
		wapper.put("success", Boolean.valueOf(true));
		wapper.put("data", "发布成功");
		log.info("发布成功");
		return wapper;
	}

	/**
	 * 根据班次模板id查询其所有的在线班次并生成可供页面展示的在线班次信息
	 * @param classesId 班次模板id
	 * @return 可供页面展示的在线班次信息
	 * @throws ParseException
	 */
	public String findListByClasses(String classesId) throws ParseException {
		ZtcClasses ztcClasses = new ZtcClasses();
		ztcClasses.setId(classesId);
		ZtcClasses classes = ztcClassesManager.searchInfoEquals(ztcClasses).get(0);
		ZtcClassesForSale classesForSale = new ZtcClassesForSale();
		classesForSale.setFkZtcClassesId(classesId);
		Date startDate = classes.getDepartureDate();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(startDate);
		calendar.add(Calendar.DATE, 35);
		Date endDate = calendar.getTime();
		List<ZtcClassesForSale> list = ztcClassesForSaleManager.searchInfoWithDateNoSort(classesForSale,
				DATE_FORMET.format(startDate), DATE_FORMET.format(endDate));
		String stringList = generateNewList(list, classes);
		return stringList;
	}

	/**
	 * 根据在线班次列表，班次模板生成可供页面展示的列表信息
	 * @param list 在线班次列表
	 * @param classes 班次模板
	 * @return 可供页面展示的列表信息
	 * @throws ParseException
	 */
	@SuppressWarnings("static-access")
	private String generateNewList(List<ZtcClassesForSale> list, ZtcClasses classes) throws ParseException {
		int preSaleDays = classes.getPreSaleDays();
		List<Date> arrangeDates = new ArrayList<>();
		Calendar calandar = Calendar.getInstance();
		calandar.setTime(classes.getDepartureDate());
		arrangeDates.add(calandar.getTime());
		for (int i = 1; i < 35; i++) {
			calandar.add(Calendar.DATE, 1);
			arrangeDates.add(calandar.getTime());
		}
		Calendar calandarOne = Calendar.getInstance();
		calandarOne.add(calandar.DATE, preSaleDays - 1);
		Date preSaleEndDate = calandarOne.getTime();
		String stringList = "[";
		for (int i = 0; i < arrangeDates.size(); i++) {
			Date selectDate = arrangeDates.get(i);
			Calendar calendarTwo = Calendar.getInstance();
			calendarTwo.setTime(selectDate);
			int dd = calendarTwo.get(Calendar.DAY_OF_MONTH);
			int month = calendarTwo.get(Calendar.MONTH) + 1;
			int weekOfMonth = calendarTwo.get(Calendar.DAY_OF_WEEK) - 1;
			String dateString = DATE_FORMET.format(selectDate);
			selectDate = DATE_FORMET.parse(dateString);
			int count = 0;
			int index = -1;
			for (int j = 0; j < list.size(); j++) {
				ZtcClassesForSale ztcClassesForSale = list.get(j);
				Date departureDate = ztcClassesForSale.getDepartureDate();
				if (departureDate.getTime() == selectDate.getTime()) {
					if (ztcClassesForSale.getTicketStatus() == 1) {
						stringList += "{\"data\":\"" + DATE_FORMET.format(departureDate) + "\",\"dd\":\"" + dd
								+ "\",\"Month\":\"" + month + "\",\"id\":\"" + ztcClassesForSale.getId()
								+ "\",\"classesId\":\"" + classes.getId() + "\",\"week\":\"" + weekOfMonth
								+ "\",\"state\":\"" + "3\"";
					} else {
						if (departureDate.getTime() < preSaleEndDate.getTime()) {
							stringList += "{\"data\":\"" + DATE_FORMET.format(departureDate) + "\",\"dd\":\"" + dd
									+ "\",\"Month\":\"" + month + "\",\"id\":\"" + ztcClassesForSale.getId()
									+ "\",\"classesId\":\"" + classes.getId() + "\",\"week\":\"" + weekOfMonth
									+ "\",\"state\":\"" + "1\"";
						} else {
							stringList += "{\"data\":\"" + DATE_FORMET.format(departureDate) + "\",\"dd\":\"" + dd
									+ "\",\"Month\":\"" + month + "\",\"id\":\"" + ztcClassesForSale.getId()
									+ "\",\"classesId\":\"" + classes.getId() + "\",\"week\":\"" + weekOfMonth
									+ "\",\"state\":\"" + "0\"";
						}
					}
					stringList += "},";
				} else {
					count++;
				}
			}
			if (count == list.size()) {
				// 拼凑当天数据
				stringList += "{\"data\":\"" + DATE_FORMET.format(selectDate) + "\",\"dd\":\"" + dd + "\",\"Month\":\""
						+ month + "\",\"classesId\":\"" + classes.getId() + "\",\"week\":\"" + weekOfMonth
						+ "\",\"state\":\"" + "2\"";
				stringList += "},";
			} else {
				if (index > 0) {
					list.remove(index);
				}
			}
		}
		if (!"[".equals(stringList)) {
			stringList.substring(0, stringList.length() - 1);
		}
		stringList += "]";
		return stringList;
	}

	/**
	 * 构造班次模板对象
	 * @param name 名称
	 * @param userId 用户id
	 * @param carType 车辆类型
	 * @param carId 车辆id
	 * @param driverId 司机id
	 * @param routeId 线路id
	 * @param remark 备注
	 * @param isRefund 是否可退票
	 * @param departureDate 发车日期
	 * @param preSaleDays 预售期
	 * @param departureType 发车类型：1.自动排班2.选择日期排班
	 * @param fsTimerbDeparture 发车前多长时间停止售票
	 * @param dayFrequencyType 发车频率按天
	 * @param weekAllDays 发车频率按周
	 * @param monthAllDays 发车频率按月
	 * @param now 当前时间
	 * @return 班次模板对象
	 * @throws ParseException
	 */
	private ZtcClasses getZtcClasses(String name, String userId, String carType, String carId, String driverId,
									 String routeId, String remark, String isRefund, String departureDate, String preSaleDays,
									 String departureType, String fsTimerbDeparture, String dayFrequencyType, String weekAllDays,
									 String monthAllDays, Date now) throws ParseException {
		ZtcClasses classes = new ZtcClasses();
		classes.setName(name);
		classes.setRemark(remark);
		classes.setTicketStatus(0);
		classes.setCarType(Integer.parseInt(carType));
		classes.setIsRefund("true".equals(isRefund) ? 1 : 0);
		classes.setPreSaleDays(Integer.parseInt(preSaleDays));
		classes.setDepartureType("1".equals(departureType.trim()) ? 0 : 1);
		if (dayFrequencyType != null && !"".equals(dayFrequencyType)) {
			int intDayFrequencyType = 1;
			if ("1".equals(dayFrequencyType)) {
				intDayFrequencyType = 2;
			} else if ("2".equals(dayFrequencyType)) {
				intDayFrequencyType = 3;
			} else if ("3".equals(dayFrequencyType)) {
				intDayFrequencyType = 4;
			} else if ("4".equals(dayFrequencyType)) {
				intDayFrequencyType = 5;
			} else if ("5".equals(dayFrequencyType)) {
				intDayFrequencyType = 6;
			} else if ("6".equals(dayFrequencyType)) {
				intDayFrequencyType = 7;
			}
			classes.setDayFrequenceType(intDayFrequencyType);
		}
		classes.setWeekAllDays(weekAllDays);
		classes.setMonthAllDays(monthAllDays);
		classes.setDepartureDate(DATE_FORMET.parse(departureDate));
		classes.setForbidSaleTimeRegionBeforeDeparture(fsTimerbDeparture);
		classes.setAddTime(now);
		classes.setFkAddUserId(userId);
		classes.setFkZtcCarId(carId);
		classes.setFkZtcDriverId(driverId);
		classes.setFkZtcRouteId(routeId);
		return classes;
	}

	/**
	 * 保存班次模板及其站点及价格
	 * @param seatNumber 座位数
	 * @param childSeatNumber 儿童座位数
	 * @param departureDate 发车日期
	 * @param ztcRouteBean 线路对象
	 * @param wapper 用于装载错误信息
	 * @param siteArray 站点集合
	 * @param priceArray 价格集合
	 * @param ztcClasses 班次模板对象
	 * @return 操作结果信息：null.失败，非null.成功
	 * @throws ParseException
	 */
	private String saveClassesInfo(String seatNumber, String childSeatNumber, String departureDate,
								   ZtcRoute ztcRouteBean, HashMap<String, Object> wapper, JSONArray siteArray, JSONArray priceArray,
								   ZtcClasses ztcClasses) throws ParseException {
		int intSeatNumber = Integer.parseInt(seatNumber);
		int intChildSeatNumber = Integer.parseInt(childSeatNumber);
		if (intChildSeatNumber > (int) (intSeatNumber * childSeatRatio)) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "儿童票不能高于成人票的10%");
			log.info("儿童票不能高于成人票的10%");
			return null;
		}
		ztcClasses.setSeatNumber(intSeatNumber);
		ztcClasses.setChildSeatNumber(intChildSeatNumber);
		ztcClasses.setFkTransportId(ztcRouteBean.getFkZtcTransportId());
		String ztcClassesId = generateZtcClasses(ztcClasses, departureDate, siteArray, priceArray);
		if (ztcClassesId == null) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "网络错误");
			log.info("网络错误");
			return null;
		}
		return ztcClassesId;
	}

	/**
	 * 保存班次模板及其站点及价格
	 * @param ztcClasses 班次模板对象
	 * @param departureDate 发车日期
	 * @param siteArray 站点集合
	 * @param priceArray 价格集合
	 * @return 操作结果信息：null.失败，非null.成功
	 * @throws ParseException
	 */
	private String generateZtcClasses(ZtcClasses ztcClasses, String departureDate, JSONArray siteArray,
									  JSONArray priceArray) throws ParseException {
		ztcClasses.setDepartureDate(DATE_FORMET.parse(departureDate));
		log.info("添加班次");
		String id = ztcClassesManager.save(ztcClasses);
		if (id != null) {
			// 获取并创建站点对象
			Map<Integer, String> siteMap = new HashMap<>();
			for (int i = 0; i < siteArray.size(); i++) {
				JSONObject object = siteArray.getJSONObject(i);
				if (object == null || object.isEmpty()) {
					continue;
				}
				ZtcClassesSite site = new ZtcClassesSite();
				String buildResult = buildClassesSite(id, object);
				if (buildResult != null) {
					site.setId(buildResult);
					siteMap.put(object.getInteger("row"), buildResult);
				} else {
					return null;
				}
			}
			String result=ztcClassesPriceDao.batchInsertPrice(id, priceArray, siteMap);
			if(!"1".equals(result)){
				return null;
			}
		}
		return id;
	}

	/**
	 * 生成班次模板站点
	 * @param id 班次模板id
	 * @param object 包含班次模板站点信息的对象
	 * @return 操作结果信息：null.失败，非null.成功
	 * @throws ParseException
	 */
	protected String buildClassesSite(String id, JSONObject object) throws ParseException {
		String time = object.getString("departureTime");
		java.sql.Time  departureTime= java.sql.Time.valueOf(time+":00");
		String daysAfterDepartureDate = object.getString("daysAfterDepartureDate");
		ZtcClassesSite ztcSite = new ZtcClassesSite();
		ztcSite.setName(object.getString("name"));
		ztcSite.setManagerPhone(object.getString("managerPhone"));
		ztcSite.setAreaCity(object.getString("areaCity"));
		ztcSite.setAreaCode(object.getString("areaCode"));
		ztcSite.setLat(object.getString("lat"));
		ztcSite.setSequence(Integer.parseInt(object.getString("row")));
		ztcSite.setDepartureTime(departureTime);
		ztcSite.setDaysAfterDepartureDate(Integer.parseInt(daysAfterDepartureDate));
		ztcSite.setFkZtcClassesId(id);
		String siteId = ztcClassesSiteManager.save(ztcSite);
		return siteId;
	}


	/**
	 * 修改班次模板
	 * @param id 班次模板id
	 * @param carType 车辆类型
	 * @param carId 车辆id
	 * @param driverId 司机id
	 * @param seatNumber 座位数
	 * @param childSeatNumber 儿童座位数
	 * @param newApplyDate 新版次应用日期
	 * @param isRefund 是否可退票
	 * @param fsTimerbDeparture  发车前多长时间停止售票
	 * @param data 梯形表数据
	 * @param departureType 发车类型：1.自动排班2.选择日期排班
	 * @param selectDepartureDates  选择的日期集合
	 * @param dayFrequencyType 发车频率按天
	 * @param weekAllDays  发车频率按周
	 * @param monthAllDays 发车频率按月
	 * @param preSaleDays 预售天数
	 * @param session
	 * @return 操作结果信息
	 * @throws ParseException
	 */
	@RequestMapping("update")
	@ResponseBody
	public HashMap<String, Object> update(String id, String carType, String carId, String driverId, String seatNumber,
										  String childSeatNumber, String newApplyDate, String isRefund, String fsTimerbDeparture, String data,
										  String departureType, String selectDepartureDates, String dayFrequencyType, String weekAllDays,
										  String monthAllDays, String preSaleDays,String autoArrangeEndDate, HttpSession session) throws ParseException {
		Date now = new Date();
		HashMap<String, Object> wapper = new HashMap<>();
		User user = (User) session.getAttribute("userInfo");
		if (user == null || "".equals(user)) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "用户未登录");
			log.info("用户未登录");
			return wapper;
		}
		ZtcTransport transport = ztcTransportManager.get(user.getTransportId());
		int transportType = transport.getType();
		if (transportType == 0 || transportType == 1 || transportType == 2) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "非运营公司或车方不可操作班次");
			log.info("非运营公司或车方不可操作班次");
			return wapper;
		}
		if (transport.getStatus() == 4) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "该用户公司已被冻结，不可修改班次");
			log.info("该用户公司已被冻结，不可修改班次");
			return wapper;
		}
		LinkedHashMap<String, String> argumentsAndRoles = new LinkedHashMap<>();
		if ("".equals(carId) || carId == null) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "请选择车辆");
			return wapper;
		}
		if ("".equals(driverId) || driverId == null) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "请选择司机");
			return wapper;
		}
		if ("".equals(fsTimerbDeparture) || fsTimerbDeparture == null) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "请填写发车前暂停售票的时间范围");
			return wapper;
		}
		argumentsAndRoles.put(fsTimerbDeparture + "#发车前暂停售票的时间范围格式如'1.01'",
				"^(([1-9][0-9]{0,9})|([0])|(([0-9].[0-9]{1,2})|([1-9][0-9]{1,7}.[0-9]{1})|([1-9][0-9]{1,6}.[0-9]{2})))$");
		if ("".equals(seatNumber) || seatNumber == null) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "请填写总座数");
			return wapper;
		}
		argumentsAndRoles.put(seatNumber + "#总票格式如'9'或'12'最小为1最大不超过65", "^(([1-9])|([1-5][0-9])|([6][0-5]))$");
		if ("".equals(childSeatNumber) || childSeatNumber == null) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "请填写儿童座数");
			return wapper;
		}
		argumentsAndRoles.put(childSeatNumber + "#儿童票格式如'0'最大不超过6", "^[0-6]$");
		if ("".equals(newApplyDate) || newApplyDate == null) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "请填写发车日期");
			return wapper;
		}
		argumentsAndRoles.put(newApplyDate + "#发车日期格式如'2017-12-26'必须大于等于当前日期",
				"^[2][0-9]{3}-(([0][1-9])|([1][0-2]))-(([1-2][0-9])|([0][1-9])|([3][0-1]))$");
		if ("".equals(preSaleDays) || preSaleDays == null) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "请填写预售期");
			return wapper;
		}
		argumentsAndRoles.put(preSaleDays + "#预售期格式如'1'必须大于等于1", "^(([1-9])|([1-9][0-9]+))$");
		examineArgument(argumentsAndRoles, wapper);
		if ("false".equals(String.valueOf(wapper.get("success")))) {
			return wapper;
		}
		JSONArray dataArray = JSON.parseArray(data);
		JSONArray siteArray = new JSONArray();
		JSONArray priceArray = new JSONArray();
		//从传入梯形表数据中得到站点数据和价格数据
		getSiteAndPriceArray(dataArray, siteArray, priceArray);
		for (int i = 0; i < siteArray.size(); i++) {
			JSONObject object = siteArray.getJSONObject(i);
			//(新版次应用日期newApplyDate)
			examineSiteInfo(newApplyDate, wapper, siteArray, i, object);
			if ("false".equals(String.valueOf(wapper.get("success")))) {
				return wapper;
			}
		}
		examinePriceInfo(priceArray, wapper);
		if ("false".equals(String.valueOf(wapper.get("success")))) {
			return wapper;
		}
		if (weekAllDays != null && !"".equals(weekAllDays)) {
			weekAllDays = weekAllDays.substring(1, weekAllDays.length() - 1);
			weekAllDays = weekAllDays.replace("\"", "");
		}
		if (monthAllDays != null && !"".equals(monthAllDays)) {
			monthAllDays = monthAllDays.substring(1, monthAllDays.length() - 1);
			monthAllDays = monthAllDays.replace("\"", "");
		}
		// 修改魔板班次
		ZtcClasses ztcClasses = new ZtcClasses();
		ztcClasses.setId(id);
		ZtcClasses ztcClassesBean = ztcClassesManager.searchInfoEquals(ztcClasses).get(0);
		if (ztcClassesBean.getTicketStatus() == 1) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "该班次已停售");
			log.info("该班次已停售");
			return wapper;
		}
		modifyClassesInvolveInfo(id, carType, carId, driverId, seatNumber, childSeatNumber, newApplyDate, isRefund,
				departureType, dayFrequencyType, weekAllDays, monthAllDays, preSaleDays, user, wapper, siteArray,
				priceArray,  fsTimerbDeparture, ztcClassesBean, now);
		if ("false".equals(String.valueOf(wapper.get("success")))) {
			return wapper;
		}
		Date startDate = DATE_FORMET.parse(newApplyDate);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(startDate);
		calendar.add(Calendar.DATE, autoArangeClassesForSaleDays);
		Date endDate = calendar.getTime();
		List<Date> departureAllDates = new ArrayList<>();
		if ("1".equals(departureType)) {
			// 如果该自动排班，自发车之日起向逐日比较：1.若该日无班次，按规则该天有，添加；2.若该日有班次，按规则该天无：若该班次已卖票，停售；若该班次无卖票，删除；3.若该日有班次，按规则该天有：若该班次已卖票，合并（状态改为在售，已售座位保留，其他添加与修改）；若该班次无卖票，替换
			departureAllDates = generateDepartureDatesOnAutoArrange(newApplyDate, dayFrequencyType, weekAllDays,
					monthAllDays,autoArrangeEndDate);
			if ("false".equals(String.valueOf(wapper.get("success")))) {
				return wapper;
			}
		} else {
			// 如果改为选择日期排班，自当下时间起向逐日比较：1.若该日无班次，按规则该天有，添加；2.若该日有班次，按规则该天无：若该班次已卖票，停售；若该班次无卖票，删除；3.若该日有班次，按规则该天有：若该班次已卖票，合并（状态改为在售，已售座位保留，其他添加与修改）；若该班次无卖票，替换
			if (!"[]".equals(selectDepartureDates) && selectDepartureDates != null) {
				selectDepartureDates = selectDepartureDates.substring(1, selectDepartureDates.length() - 1);
				startDate = new Date();
				endDate = generateDepartureDatesOnDateArrange(selectDepartureDates, startDate, calendar,
						departureAllDates);
				if ("false".equals(String.valueOf(wapper.get("success")))) {
					return wapper;
				}
			} else {
				wapper.put("success", Boolean.valueOf(false));
				wapper.put("msg", "定时发班请选择日期");
				log.info("定时发班请选择日期");
				return wapper;
			}
		}
		ZtcClassesForSale ztcClassesForSale = new ZtcClassesForSale();
		ztcClassesForSale.setFkZtcClassesId(id);
		List<ZtcClassesForSale> ztcClassesForSales = ztcClassesForSaleManager.searchInfoWithDate(ztcClassesForSale,
				DATE_FORMET.format(startDate), DATE_FORMET.format(endDate));
		// 修改在售班次价格信息
		if ("1".equals(departureType)) {
			modifyClassesForSaleInvolveInfo(carType, carId, driverId, seatNumber, childSeatNumber, isRefund,
					fsTimerbDeparture, user, wapper, dataArray, siteArray, priceArray, ztcClassesBean,
					departureAllDates, ztcClassesForSales, now);
			if ("false".equals(String.valueOf(wapper.get("success")))) {
				return wapper;
			}
		} else {
			if (!"".equals(selectDepartureDates) && selectDepartureDates != null) {
				modifyClassesForSaleInvolveInfo(carType, carId, driverId, seatNumber, childSeatNumber, isRefund,
						fsTimerbDeparture, user, wapper, dataArray, siteArray, priceArray,
						ztcClassesBean, departureAllDates, ztcClassesForSales, now);
				if ("false".equals(String.valueOf(wapper.get("success")))) {
					return wapper;
				}
			}
		}
		wapper.put("success", Boolean.valueOf(true));
		wapper.put("data", "修改成功");
		log.info("修改成功");
		return wapper;
	}

	/**
	 * 修改班次模板信息及其站点及价格
	 * @param id 班次模板id
	 * @param carType 车辆类型
	 * @param carId 车辆id
	 * @param driverId 司机id
	 * @param seatNumber 座位数
	 * @param childSeatNumber 儿童座位数
	 * @param newApplyDate 新班次模板应用日期
	 * @param isRefund 是否可退票
	 * @param departureType 发车类型：1.自动排班2.选择日期排班
	 * @param dayFrequencyType 发车频率按天
	 * @param weekAllDays 发车频率按周
	 * @param monthAllDays 发车频率按月
	 * @param preSaleDays 预售天数
	 * @param user 登录用户对象
	 * @param wapper 用于装载错误信息
	 * @param siteArray 站点集合
	 * @param priceArray 价格集合
	 * @param fsTimerbDeparture 发车前多长时间停止售票
	 * @param ztcClassesBean 班次模板对象
	 * @param now 当前时间
	 * @throws ParseException
	 */
	private void modifyClassesInvolveInfo(String id, String carType, String carId, String driverId, String seatNumber,
										  String childSeatNumber, String newApplyDate, String isRefund, String departureType, String dayFrequencyType,
										  String weekAllDays, String monthAllDays, String preSaleDays, User user, HashMap<String, Object> wapper,
										  JSONArray siteArray, JSONArray priceArray, String fsTimerbDeparture,
										  ZtcClasses ztcClassesBean, Date now) throws ParseException {
		modifyClassesInfo(carType, carId, driverId, seatNumber, childSeatNumber, newApplyDate, isRefund, departureType,
				dayFrequencyType, weekAllDays, monthAllDays, preSaleDays, user, wapper, fsTimerbDeparture,
				ztcClassesBean, now);
		if ("false".equals(String.valueOf(wapper.get("success")))) {
			return;
		}
		String ztcClassesBeanId = ztcClassesManager.update(ztcClassesBean);
		if ("0".equals(ztcClassesBeanId)) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "网络错误");
			log.info("网络错误");
			return;
		}
		// 修改模板站点
		modifyClassesSiteInfo(id, wapper, siteArray);
		if ("false".equals(wapper.get("success"))) {
			return;
		}
		// 修改模板价格
		modifyClassesPriceInfo(id, wapper, priceArray,user,now);
		if ("false".equals(wapper.get("success"))) {
			return;
		}
	}

	/**
	 * 修改班次模板信息
	 * @param carType 车辆类型
	 * @param carId 车辆id
	 * @param driverId 司机id
	 * @param seatNumber 座位数
	 * @param childSeatNumber 儿童座位数
	 * @param newApplyDate 新班次模板应用日期
	 * @param isRefund 是否可退票
	 * @param departureType 发车类型：1.自动排班2.选择日期排班
	 * @param dayFrequencyType 发车频率按天
	 * @param weekAllDays 发车频率按周
	 * @param monthAllDays 发车频率按月
	 * @param preSaleDays 预售天数
	 * @param user  登录用户对象
	 * @param wapper 用于装载错误信息
	 * @param fsTimerbDeparture 发车前多长时间停止售票
	 * @param ztcClassesBean 班次模板对象
	 * @param now 当前时间
	 * @throws ParseException
	 */
	private void modifyClassesInfo(String carType, String carId, String driverId, String seatNumber,
								   String childSeatNumber, String newApplyDate, String isRefund, String departureType, String dayFrequencyType,
								   String weekAllDays, String monthAllDays, String preSaleDays, User user, HashMap<String, Object> wapper,
								   String fsTimerbDeparture, ZtcClasses ztcClassesBean, Date now) throws ParseException {
		ztcClassesBean.setModifyTime(now);
		ztcClassesBean.setFkModifyUserId(user == null ? "" : user.getId());
		ztcClassesBean.setCarType(Integer.parseInt(carType));
		ztcClassesBean.setFkZtcCarId(carId);
		ztcClassesBean.setFkZtcDriverId(driverId);
		ztcClassesBean.setIsRefund("true".equals(isRefund) ? 1 : 0);
		ztcClassesBean.setDepartureDate(DATE_FORMET.parse(newApplyDate));
		ztcClassesBean.setPreSaleDays(Integer.parseInt(preSaleDays));
		ztcClassesBean.setDepartureType("1".equals(departureType) ? 0 : 1);
		int intSeatNumber = Integer.parseInt(seatNumber);
		int intChildSeatNumber = Integer.parseInt(childSeatNumber);
		if (intChildSeatNumber > (int) (intSeatNumber * childSeatRatio)) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "儿童票不能高于成人票的10%");
			log.info("儿童票不能高于成人票的10%");
			return;
		}
		ztcClassesBean.setSeatNumber(intSeatNumber);
		ztcClassesBean.setChildSeatNumber(intChildSeatNumber);
		ztcClassesBean.setModifyTime(new Date());
		ztcClassesBean.setForbidSaleTimeRegionBeforeDeparture(fsTimerbDeparture);
		if (dayFrequencyType != null && !"".equals(dayFrequencyType)) {
			int intDayFrequencyType = 1;
			if ("1".equals(dayFrequencyType)) {
				intDayFrequencyType = 2;
			} else if ("2".equals(dayFrequencyType)) {
				intDayFrequencyType = 3;
			} else if ("3".equals(dayFrequencyType)) {
				intDayFrequencyType = 4;
			} else if ("4".equals(dayFrequencyType)) {
				intDayFrequencyType = 5;
			} else if ("5".equals(dayFrequencyType)) {
				intDayFrequencyType = 6;
			} else if ("6".equals(dayFrequencyType)) {
				intDayFrequencyType = 7;
			}
			ztcClassesBean.setDayFrequenceType(intDayFrequencyType);
			ztcClassesBean.setWeekAllDays(null);
			ztcClassesBean.setMonthAllDays(null);
		} else if (weekAllDays != null && !"".equals(weekAllDays)) {
			ztcClassesBean.setDayFrequenceType(null);
			ztcClassesBean.setWeekAllDays(weekAllDays);
			ztcClassesBean.setMonthAllDays(null);
		} else if (monthAllDays != null && !"".equals(monthAllDays)) {
			ztcClassesBean.setDayFrequenceType(null);
			ztcClassesBean.setWeekAllDays(null);
			ztcClassesBean.setMonthAllDays(monthAllDays);
		} else {
			ztcClassesBean.setDayFrequenceType(null);
			ztcClassesBean.setWeekAllDays(null);
			ztcClassesBean.setMonthAllDays(null);
		}
	}

	/**
	 * 按照自动排班规则生成发车日期集合
	 * @param newApplyDate 新班次模板应用日期
	 * @param dayFrequencyType 发车频率按天
	 * @param weekAllDays 发车频率按周
	 * @param monthAllDays 发车频率按月
	 * @return 返回发车日期集合
	 * @throws ParseException
	 */
	private List<Date> generateDepartureDatesOnAutoArrange(String newApplyDate, String dayFrequencyType,
														   String weekAllDays, String monthAllDays,String autoArrangeEndDate) throws ParseException {
		List<Date> departureAllDates = new ArrayList<Date>();
		Date departureDate = DATE_FORMET.parse(newApplyDate);
		if (!"".equals(dayFrequencyType) && dayFrequencyType != null) {
			int intDayFrequencyType = 1;
			if ("1".equals(dayFrequencyType)) {
				intDayFrequencyType = 2;
			} else if ("2".equals(dayFrequencyType)) {
				intDayFrequencyType = 3;
			} else if ("3".equals(dayFrequencyType)) {
				intDayFrequencyType = 4;
			} else if ("4".equals(dayFrequencyType)) {
				intDayFrequencyType = 5;
			} else if ("5".equals(dayFrequencyType)) {
				intDayFrequencyType = 6;
			} else if ("6".equals(dayFrequencyType)) {
				intDayFrequencyType = 7;
			}
			for (int i = 0; i <= autoArangeClassesForSaleDays; i = i + intDayFrequencyType) {
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(departureDate);
				calendar.add(Calendar.DATE, i);
				if(autoArrangeEndDate!=null&&!"".equals(autoArrangeEndDate)){
					Date autoArrangeEndActualDate=DATE_FORMET.parse(autoArrangeEndDate);
					if(calendar.getTime().getTime()<=autoArrangeEndActualDate.getTime()){
						departureAllDates.add(calendar.getTime());
					}
				}else{
					departureAllDates.add(calendar.getTime());
				}
			}
		}
		if (!"".equals(weekAllDays) && weekAllDays != null&&!",".equals(weekAllDays)) {
			String[] weekDays = weekAllDays.split(",");
			departureAllDates.add(departureDate);
			for (int i = 1; i <= autoArangeClassesForSaleDays; i++) {
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(departureDate);
				calendar.add(Calendar.DATE, i);
				if(autoArrangeEndDate!=null&&!"".equals(autoArrangeEndDate)) {
					Date autoArrangeEndActualDate = DATE_FORMET.parse(autoArrangeEndDate);
					if(calendar.getTime().getTime()<=autoArrangeEndActualDate.getTime()){
						for (String day : weekDays) {
							if (!"".equals(day)) {
								if (Integer.parseInt(day) == calendar.get(Calendar.DAY_OF_WEEK) - 1) {
									departureAllDates.add(calendar.getTime());
								}
							}
						}
					}
				}else{
					for (String day : weekDays) {
						if (!"".equals(day)) {
							if (Integer.parseInt(day) == calendar.get(Calendar.DAY_OF_WEEK) - 1) {
								departureAllDates.add(calendar.getTime());
							}
						}
					}
				}
			}
		}
		if (!"".equals(monthAllDays) && monthAllDays != null&&!",".equals(monthAllDays)) {
			String[] monthDays = monthAllDays.split(",");
			departureAllDates.add(departureDate);
			for (int i = 1; i <= autoArangeClassesForSaleDays; i++) {
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(departureDate);
				calendar.add(Calendar.DATE, i);
				if(autoArrangeEndDate!=null&&!"".equals(autoArrangeEndDate)) {
					Date autoArrangeEndActualDate = DATE_FORMET.parse(autoArrangeEndDate);
					if(calendar.getTime().getTime()<=autoArrangeEndActualDate.getTime()) {
						for (String day : monthDays) {
							if (!"".equals(day)) {
								if (Integer.parseInt(day) == calendar.get(Calendar.DATE)) {
									departureAllDates.add(calendar.getTime());
								}
							}
						}
					}
				}else{
					for (String day : monthDays) {
						if (!"".equals(day)) {
							if (Integer.parseInt(day) == calendar.get(Calendar.DATE)) {
								departureAllDates.add(calendar.getTime());
							}
						}
					}
				}
			}
		}
		return departureAllDates;
	}

	/**
	 * 按照手动选择的发车日期生成发车日期集合，同时根据起始日期生成结束日期
	 * @param selectDepartureDates 手动选择的发车日期字符串集合
	 * @param startDate 开始时间
	 * @param calendar 日历对象用于生成发车日期
	 * @param departureAllDates 发车日期集合
	 * @return 结束日期
	 * @throws ParseException
	 */
	private Date generateDepartureDatesOnDateArrange(String selectDepartureDates, Date startDate, Calendar calendar,
													 List<Date> departureAllDates) throws ParseException {
		Date endDate = new Date();
		calendar.setTime(startDate);
		calendar.add(Calendar.DATE, autoArangeClassesForSaleDays * 2);
		endDate = calendar.getTime();
		String[] departureDates = selectDepartureDates.split(",");
		for (int i = 0; i < departureDates.length; i++) {
			String selectDepartureDate = departureDates[i];
			selectDepartureDate = selectDepartureDate.substring(1, selectDepartureDate.length() - 1);
			Date date = DATE_TIME_FORMET.parse(selectDepartureDate + " " + "00:00:00");
			departureAllDates.add(date);
		}
		return endDate;
	}

	/**
	 * 根据如果改为选择日期排班，自当下时间起向逐日比较：1.若该日无班次，按规则该天有，添加；2.若该日有班次，按规则该天无：若该班次已卖票，停售；若该班次无卖票，删除；3.若该日有班次，按规则该天有：若该班次已卖票，合并（状态改为在售，已售座位保留，其他添加与修改）；若该班次无卖票，替换
	 * 修改在线班次
	 * @param carType 车辆类型
	 * @param carId 车辆id
	 * @param driverId 司机id
	 * @param seatNumber 座位数
	 * @param childSeatNumber 儿童座位数
	 * @param isRefund 是否可退票
	 * @param fsTimerbDeparture 发车前多长时间停止售票
	 * @param user  登录用户对象
	 * @param wapper 用于装载操作结果信息
	 * @param dataArray 班次模板梯形表数据集合
	 * @param siteArray 班次模板站点集合
	 * @param priceArray 班次模板价格集合
	 * @param ztcClassesBean 班次模板对象
	 * @param departureAllDates 发车日期集合
	 * @param ztcClassesForSales 班次模板的在线班次集合
	 * @param now 当前时间
	 * @throws ParseException
	 */
	private void modifyClassesForSaleInvolveInfo(String carType, String carId, String driverId, String seatNumber,
												 String childSeatNumber, String isRefund, String fsTimerbDeparture, User user,
												 HashMap<String, Object> wapper, JSONArray dataArray, JSONArray siteArray, JSONArray priceArray, ZtcClasses ztcClassesBean, List<Date> departureAllDates,
												 List<ZtcClassesForSale> ztcClassesForSales, Date now) throws ParseException {
		for (int i = 0; i < departureAllDates.size(); i++) {
			Date getDepartureDate = departureAllDates.get(i);
			int index = -1;
			for (int j = 0; j < ztcClassesForSales.size(); j++) {
				ZtcClassesForSale classesForSale = ztcClassesForSales.get(j);
				// 情况3
				if (classesForSale.getDepartureDate().getTime() == getDepartureDate.getTime()) {
					index = j;
					ZtcClassesPriceForSale price = new ZtcClassesPriceForSale();
					price.setFkClassesForSaleId(classesForSale.getId());
					List<ZtcClassesPriceForSale> prices = ztcClassesPriceForSaleManager.searchInfoEquals(price);
					boolean isHaveSaleTicket = examineIsHaveSale(prices);
					if (isHaveSaleTicket) {
						// 合并
						mergerClassesForSaleInfo(seatNumber, childSeatNumber, user, wapper, siteArray, priceArray,
								classesForSale, prices, fsTimerbDeparture, now);
						if ("false".equals(String.valueOf(wapper.get("success")))) {
							return;
						}
					} else {
						// 替换
						deleteClassesForSaleInfo(wapper, classesForSale);
						insertClassesForSaleInfo(carType, carId, driverId, seatNumber, childSeatNumber, isRefund,
								fsTimerbDeparture, user, wapper, dataArray, siteArray, priceArray, ztcClassesBean, getDepartureDate, now);
						if ("false".equals(String.valueOf(wapper.get("success")))) {
							return;
						}
					}
				}
			}
			if (index != -1) {
				ztcClassesForSales.remove(index);
				continue;
			} else {
				// 情况1:添加
				insertClassesForSaleInfo(carType, carId, driverId, seatNumber, childSeatNumber, isRefund,
						fsTimerbDeparture, user, wapper, dataArray, siteArray, priceArray, ztcClassesBean, getDepartureDate, now);
				if ("false".equals(String.valueOf(wapper.get("success")))) {
					return;
				}
			}
		}
		// 情况2
		if (ztcClassesForSales.size() > 0) {
			handleSituationTwo(user, wapper, siteArray, ztcClassesForSales,now);
			if ("false".equals(String.valueOf(wapper.get("success")))) {
				return;
			}
		}
	}

	/**
	 * 若该日有班次，按规则该天有：若该班次已卖票，合并（状态改为在售，已售座位保留，其他添加与修改）
	 * @param seatNumber 座位号
	 * @param childSeatNumber 儿童座位号
	 * @param user 登录用户对象
	 * @param wapper 用于装载操作结果信息
	 * @param siteArray 班次模板站点集合
	 * @param priceArray 班次模板价格集合
	 * @param classesForSale 某在线班次对象
	 * @param prices 某在线班次的价格集合
	 * @param fsTimerbDeparture 发车前多长时间停止售票
	 * @param now 当前时间
	 */
	private void mergerClassesForSaleInfo(String seatNumber, String childSeatNumber, User user,
										  HashMap<String, Object> wapper, JSONArray siteArray, JSONArray priceArray, ZtcClassesForSale classesForSale,
										  List<ZtcClassesPriceForSale> prices, String fsTimerbDeparture, Date now) {
		int stopPriceCount = 0;
		int onPriceCount = 0;
		for (int k = 0; k < prices.size(); k++) {
			// 需要修改价格和距离
			ZtcClassesPriceForSale priceForSale = prices.get(k);
			ZtcClassesSiteForSale site = new ZtcClassesSiteForSale();
			site.setId(priceForSale.getFkStartClassesSiteForSaleId());
			ZtcClassesSiteForSale startSite = ztcClassesSiteForSaleManager.searchInfoEquals(site).get(0);
			site.setId(priceForSale.getFkEndClassesSiteForSaleId());
			ZtcClassesSiteForSale endSite = ztcClassesSiteForSaleManager.searchInfoEquals(site).get(0);
			JSONArray priceArrayTwo = new JSONArray();
			priceArrayTwo = priceArray;
			int priceIndex = -1;
			for (int l = 0; l < priceArrayTwo.size(); l++) {
				JSONObject priceValue = priceArrayTwo.getJSONObject(l);
				int row = priceValue.getInteger("row");
				int col = priceValue.getInteger("col");
				String floatPrice = priceValue.getString("price");
				String distance = priceValue.getString("distance");
				if (row == startSite.getSequence() || col == endSite.getSequence()) {
					priceForSale.setPrice(floatPrice);
					priceForSale.setDistance(distance);
					priceForSale.setModifyTime(now);
					priceForSale.setFkModifyUserId(user.getId());
					priceIndex = l;
					break;
				}
			}
			if (priceIndex > 0) {
				priceArrayTwo.remove(priceIndex);
			}
			ZtcOrder ztcOrder = new ZtcOrder();
			ztcOrder.setFkZtcClassesPriceForSaleId(priceForSale.getId());
			int saleChildSeatNumber = 0;
			List<ZtcOrder> orders = orderManager.searchInfo(ztcOrder);
			List<ZtcOrderTicket> orderTickets = new ArrayList<ZtcOrderTicket>();
			if (orders != null && orders.size() > 0) {
				for (int l = 0; l < orders.size(); l++) {
					ZtcOrder order = orders.get(l);
					ZtcOrderTicket ticket = new ZtcOrderTicket();
					ticket.setFkOrderId(order.getId());
					ticket.setStatus(0);
					orderTickets.addAll(orderTicketManager.searchInfoEquals(ticket));
				}
			}

			if (orderTickets.size() > 0) {
				for (int l = 0; l < orderTickets.size(); l++) {
					ZtcOrderTicket ticket = orderTickets.get(l);
					if (ticket.getSeatType() == 3) {
						saleChildSeatNumber++;
					}
				}
			}
			String seatInfo = priceForSale.getSeatInfo();
			if("".equals(seatInfo)||"()".equals(seatInfo)){
				continue;
			}
			String[] seatInfos = seatInfo.split("\\u0029,");
			int[] seatNumbers = new int[seatInfos.length];
			for (int l = 0; l < seatInfos.length; l++) {
				String seat = seatInfos[l];
				if ("".equals(seat)) {
					continue;
				}
				int seatIndex = seat.indexOf(")");
				if (seatIndex > 0) {
					seat = seat.substring(1, seatIndex);
				} else {
					seat = seat.substring(1);
				}
				String[] tags = seat.split(",");
				seatNumbers[l] = Integer.parseInt(tags[0]);
			}
			Arrays.sort(seatNumbers);
			if (Integer.parseInt(seatNumber) < seatNumbers.length) {
				// 减少总座位数，删掉多余座位信息，重设儿童座位数
				stopPriceCount = subClassesPriceForSaleSeatInfo(seatNumber, childSeatNumber, priceForSale,
						saleChildSeatNumber, seatInfos, seatNumbers);
			} else {
				// 添加总座位数,添加少的座位信息，重设儿童座位数
				onPriceCount = addClassesPriceForSaleSeatInfo(seatNumber, childSeatNumber, priceForSale,
						saleChildSeatNumber, seatInfos, seatNumbers);
			}
			ztcClassesPriceForSaleManager.update(priceForSale);
		}
		classesForSale.setForbidSaleTimeRegionBeforeDeparture(fsTimerbDeparture);
		classesForSale.setChildSeatNumber(Integer.parseInt(childSeatNumber));
		classesForSale.setSeatNumber(Integer.parseInt(seatNumber));
		classesForSale.setModifyTime(now);
		classesForSale.setFkModifyUserId(user == null ? "" : user.getId());
		if (stopPriceCount == priceArray.size()) {
			classesForSale.setTicketStatus(1);
		} else {
			if (onPriceCount > 0) {
				classesForSale.setTicketStatus(0);
			}
		}
		modifySiteForSaleInfo(wapper, siteArray, classesForSale);
		if ("false".equals(String.valueOf(wapper.get("success")))) {
			return;
		}
		String result = ztcClassesForSaleManager.update(classesForSale);
		if ("0".equals(result)) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "网络错误");
			log.info("网络错误");
			return;
		}
	}

	/**
	 * 减少总座位数，删掉多余座位信息，重设儿童座位数
	 * @param seatNumber 总座数
	 * @param childSeatNumber 儿童座位数
	 * @param priceForSale 在线班次价格对象
	 * @param saleChildSeatNumber 已售儿童座位
	 * @param seatInfos 座位信息
	 * @param seatNumbers  座位号集合
	 * @return 停售的在线班次数量
	 */
	private int subClassesPriceForSaleSeatInfo(String seatNumber, String childSeatNumber,
											   ZtcClassesPriceForSale priceForSale, int saleChildSeatNumber, String[] seatInfos, int[] seatNumbers) {
		int stopPriceCount = 0;
		int subSeatNumber = seatNumbers.length - Integer.parseInt(seatNumber);
		String newSeatInfo = "";
		int commonSaleSeatNumber = 0;
		int specialSaleSeatNumber = 0;
		int highSaleSeatNumber = 0;
		int commonOnSeatNumber = 0;
		int specialOnSeatNumber = 0;
		int highOnSeatNumber = 0;
		for (int l = 0; l < seatInfos.length; l++) {
			String seat = seatInfos[l];
			if ("".equals(seat)) {
				continue;
			}
			int seatIndex = seat.indexOf(")");
			if (seatIndex > 0) {
				seat = seat.substring(1, seatIndex);
			} else {
				seat = seat.substring(1);
			}
			String[] tags = seat.split(",");
			if (tags[1].equals("1")) {
				newSeatInfo += "(" + seat + "),";
				if ("0".equals(tags[3])) {
					commonSaleSeatNumber++;
				} else if ("1".equals(tags[3])) {
					specialSaleSeatNumber++;
				} else {
					highSaleSeatNumber++;
				}
			} else if (tags[1].equals("2")) {
				//newSeatInfo += "(" + seat + "),";
				subSeatNumber--;
			} else {
				if (subSeatNumber > 0) {
					subSeatNumber--;
					//newSeatInfo += "(" + tags[0] + ",2," + tags[2] + "," + tags[3] + "),";
				} else {
					newSeatInfo += "(" + tags[0] + "," + tags[1] + "," + priceForSale.getPrice() + "," + tags[3] + "),";
					if ("0".equals(tags[3])) {
						commonOnSeatNumber++;
					} else if ("1".equals(tags[3])) {
						specialOnSeatNumber++;
					} else {
						highOnSeatNumber++;
					}
				}
			}
		}
		if (!"".equals(newSeatInfo)) {
			newSeatInfo = newSeatInfo.substring(0, newSeatInfo.length() - 1);
		}
		// 计算剩余儿童座位数
		int seatInfoNumber = commonSaleSeatNumber + specialSaleSeatNumber + highSaleSeatNumber + commonOnSeatNumber
				+ specialOnSeatNumber + highOnSeatNumber;
		int calculateChildSeatNumber = (int) ((seatInfoNumber) * childSeatRatio);
		if (calculateChildSeatNumber - saleChildSeatNumber < Integer.parseInt(childSeatNumber)) {
			if (calculateChildSeatNumber - saleChildSeatNumber > 0) {
				priceForSale.setRemainChildSeatNumber(calculateChildSeatNumber - saleChildSeatNumber);
			} else {
				priceForSale.setRemainChildSeatNumber(0);
			}
		} else {
			priceForSale.setRemainChildSeatNumber(Integer.parseInt(childSeatNumber));
		}
		if (!"".equals(newSeatInfo)&&!"()".equals(newSeatInfo)) {
			priceForSale.setSeatInfo(newSeatInfo);
		}
		int remainSeatNumber = commonOnSeatNumber + specialOnSeatNumber + highOnSeatNumber;
		priceForSale.setRemainSeatNumber(remainSeatNumber);
		if (remainSeatNumber <= 0) {
			priceForSale.setStatus(1);
			stopPriceCount++;
		}
		return stopPriceCount;
	}

	/**
	 * 添加总座位数,添加少的座位信息，重设儿童座位数
	 * @param seatNumber 总座数
	 * @param childSeatNumber 儿童座位数
	 * @param priceForSale 在线班次价格对象
	 * @param saleChildSeatNumber 已售的儿童票座位数
	 * @param seatInfos 座位信息
	 * @param seatNumbers 座位号集合
	 * @return 在售的在线班次价格数
	 */
	private int addClassesPriceForSaleSeatInfo(String seatNumber, String childSeatNumber,
											   ZtcClassesPriceForSale priceForSale, int saleChildSeatNumber, String[] seatInfos, int[] seatNumbers) {
		int onPriceCount = 0;
		String newSeatInfo = "";
		int actualAddSeatNumber = Integer.parseInt(seatNumber) - seatNumbers.length;
		int orignalAddSeatNumber = actualAddSeatNumber;
		int onSeatNumber = 0;
		int recoverySeatNumber = 0;
		int saleSeatNumber = 0;
		for (int l = 0; l < seatInfos.length; l++) {
			String seat = seatInfos[l];
			if ("".equals(seat)) {
				continue;
			}
			int seatIndex = seat.indexOf(")");
			if (seatIndex > 0) {
				seat = seat.substring(1, seatIndex);
			} else {
				seat = seat.substring(1);
			}
			String[] tags = seat.split(",");
			if ("0".equals(tags[1])) {
				newSeatInfo += "(" + tags[0] + "," + tags[1] + "," + priceForSale.getPrice() + "," + tags[3] + "),";
				onSeatNumber++;
			} else if ("2".equals(tags[1])) {
				if (recoverySeatNumber < actualAddSeatNumber) {
					newSeatInfo += "(" + tags[0] + ",0," + priceForSale.getPrice() + "," + tags[3] + "),";
					recoverySeatNumber++;
				}else{
					newSeatInfo += "(" + tags[0] + "," + tags[1] + "," + tags[2] + "," + tags[3] + "),";
				}
			} else if ("1".equals(tags[1])) {
				newSeatInfo += "(" + tags[0] + "," + tags[1] + "," + tags[2] + "," + tags[3] + "),";
				saleSeatNumber++;
			}
		}
		actualAddSeatNumber = actualAddSeatNumber - recoverySeatNumber;
		if (actualAddSeatNumber > 0) {
			int firstNumber = seatNumbers[0];
			if (firstNumber > 1) {
				for (int l = 1; l < firstNumber; l++) {
					if (actualAddSeatNumber > 0) {
						newSeatInfo += "(" + l + ",0," + priceForSale.getPrice() + ",0),";
						actualAddSeatNumber--;
					} else {
						break;
					}
				}
			}
			if (actualAddSeatNumber > 0) {
				for (int l = 0; l < seatNumbers.length - 1; l++) {
					int start = seatNumbers[l];
					int end = seatNumbers[l + 1];
					for (int m = start + 1; m < end; m++) {
						if (actualAddSeatNumber > 0) {
							newSeatInfo += "(" + m + ",0," + priceForSale.getPrice() + ",0),";
							actualAddSeatNumber--;
						} else {
							break;
						}
					}
					if (actualAddSeatNumber <= 0) {
						break;
					}
				}
			}
			if (actualAddSeatNumber > 0) {
				int lastNumber = seatNumbers[seatNumbers.length - 1];
				for (int l = lastNumber + 1; l < 66; l++) {
					if (actualAddSeatNumber > 0) {
						newSeatInfo += "(" + l + ",0," + priceForSale.getPrice() + ",0),";
						actualAddSeatNumber--;
					} else {
						break;
					}
				}
			}
		}
		if (!"".equals(newSeatInfo)) {
			newSeatInfo = newSeatInfo.substring(0, newSeatInfo.length() - 1);
		}
		// 计算剩余儿童座位数
		int seatInfoNumber = onSeatNumber + recoverySeatNumber + saleSeatNumber + orignalAddSeatNumber
				- actualAddSeatNumber;
		int calculateChildSeatNumber = (int) (seatInfoNumber * childSeatRatio);
		if (calculateChildSeatNumber - saleChildSeatNumber < Integer.parseInt(childSeatNumber)) {
			if (calculateChildSeatNumber - saleChildSeatNumber > 0) {
				priceForSale.setRemainChildSeatNumber(calculateChildSeatNumber - saleChildSeatNumber);
			} else {
				priceForSale.setRemainChildSeatNumber(0);
			}
		} else {
			priceForSale.setRemainChildSeatNumber(Integer.parseInt(childSeatNumber));
		}
		if(!"".equals(newSeatInfo)&&!"()".equals(newSeatInfo)){
			priceForSale.setSeatInfo(newSeatInfo);
		}
		int remainSeatNumber = onSeatNumber + recoverySeatNumber + orignalAddSeatNumber - actualAddSeatNumber;
		if (priceForSale.getRemainSeatNumber() < remainSeatNumber) {
			priceForSale.setStatus(0);
			onPriceCount++;
		}
		priceForSale.setRemainSeatNumber(remainSeatNumber);
		return onPriceCount;
	}

	/**
	 * 添加在线班次
	 * @param carType 车辆类型
	 * @param carId 车辆id
	 * @param driverId 司机id
	 * @param seatNumber 总座位数
	 * @param childSeatNumber 儿童座位数
	 * @param isRefund 是否可退票
	 * @param fsTimerbDeparture 离发车前多长时间停售
	 * @param user 登录用户对象
	 * @param wapper 用于装载操作结果信息
	 * @param dataArray 班次模板梯形表数据
	 * @param siteArray 班次模板站点集合
	 * @param priceArray 班次模板价格集合
	 * @param ztcClassesBean 班次模板对象
	 * @param getDepartureDate 发车日期
	 * @param now 当前时间
	 * @throws ParseException
	 */
	private void insertClassesForSaleInfo(String carType, String carId, String driverId, String seatNumber,
										  String childSeatNumber, String isRefund, String fsTimerbDeparture, User user,
										  HashMap<String, Object> wapper, JSONArray dataArray, JSONArray siteArray, JSONArray priceArray,ZtcClasses ztcClassesBean, Date getDepartureDate, Date now)
			throws ParseException {
		ZtcClassesForSale newClassesForSale =new ZtcClassesForSale();
		newClassesForSale.setName(ztcClassesBean.getName());
		newClassesForSale.setRemark(ztcClassesBean.getRemark());
		newClassesForSale.setStatus(0);
		newClassesForSale.setTicketStatus(0);
		newClassesForSale.setType(0);
		newClassesForSale.setCarType(Integer.parseInt(carType));
		newClassesForSale.setIsRefund("true".equals(isRefund) ? 1 : 0);
		newClassesForSale.setDepartureDate(getDepartureDate);
		newClassesForSale.setForbidSaleTimeRegionBeforeDeparture(fsTimerbDeparture);
		newClassesForSale.setAddTime(now);
		newClassesForSale.setFkAddUserId(user == null ? "" : user.getId());
		newClassesForSale.setFkZtcCarId(carId);
		newClassesForSale.setFkZtcDriverId(driverId);
		newClassesForSale.setFkZtcClassesId(ztcClassesBean.getId());
		newClassesForSale.setChildSeatNumber(Integer.parseInt(childSeatNumber));
		newClassesForSale.setSeatNumber(Integer.parseInt(seatNumber));
		newClassesForSale.setFkTransportId(ztcClassesBean.getFkTransportId());
		getSiteAndPriceWithSeatInfoArray(dataArray, siteArray, priceArray, seatNumber);
		String addResult = generateClassesForSale(newClassesForSale, siteArray, priceArray, childSeatNumber, seatNumber);
		if (addResult == null) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "网络错误");
			log.info("网络错误");
			return;
		}
	}

	/**
	 * 若该日有班次，按规则该天无：若该班次已卖票，停售；若该班次无卖票，删除
	 * @param user 登录用户对象
	 * @param wapper 用于装载操作结果信息
	 * @param siteArray 班次模板站点集合
	 * @param ztcClassesForSales 在线班次集合
	 */
	private void handleSituationTwo(User user, HashMap<String, Object> wapper, JSONArray siteArray,
									List<ZtcClassesForSale> ztcClassesForSales,Date now) {
		for (int i = 0; i < ztcClassesForSales.size(); i++) {
			ZtcClassesForSale classesForSale = ztcClassesForSales.get(i);
			ZtcClassesPriceForSale ztcClassesPriceForSale = new ZtcClassesPriceForSale();
			ztcClassesPriceForSale.setFkClassesForSaleId(classesForSale.getId());
			List<ZtcClassesPriceForSale> ztcClassesPriceForSales = ztcClassesPriceForSaleManager
					.searchInfoEquals(ztcClassesPriceForSale);
			boolean isHaveSaleTicket = examineIsHaveSale(ztcClassesPriceForSales);
			if (isHaveSaleTicket) {
				// 修改站点负责人电话
				modifySiteForSaleInfo(wapper, siteArray, classesForSale);
				if ("false".equals(String.valueOf(wapper.get("success")))) {
					return;
				}
				classesForSale.setModifyTime(new Date());
				classesForSale.setFkModifyUserId(user == null ? "" : user.getId());
				String result = ztcClassesForSaleManager.stopSell(classesForSale,user,now);
				if ("0".equals(result)) {
					wapper.put("success", Boolean.valueOf(false));
					wapper.put("msg", "网络错误");
					log.info("网络错误");
					return;
				}
			} else {
				deleteClassesForSaleInfo(wapper, classesForSale);
				if ("false".equals(String.valueOf(wapper.get("success")))) {
					return;
				}
			}
		}
	}

	/**
	 * 检验某在线班次价格是否卖了票
	 * @param prices 在线班次价格集合
	 * @return true.已售，false.未售
	 */
	private boolean examineIsHaveSale(List<ZtcClassesPriceForSale> prices) {
		boolean isHaveSaleTicket = false;
		for (int k = 0; k < prices.size(); k++) {
			ZtcClassesPriceForSale priceForSale = prices.get(k);
			String seatInfo = priceForSale.getSeatInfo();
			if("".equals(seatInfo)||"()".equals(seatInfo)){
				continue;
			}
			String[] seatInfos = seatInfo.split("\\u0029,");
			for (int l = 0; l < seatInfos.length; l++) {
				String seat = seatInfos[l];
				if ("".equals(seat)) {
					continue;
				}
				int seatIndex = seat.indexOf(")");
				if (seatIndex > 0) {
					seat = seat.substring(1, seatIndex);
				} else {
					seat = seat.substring(1);
				}
				String[] tags = seat.split(",");
				if ("1".equals(tags[1])) {
					isHaveSaleTicket = true;
				}
			}
		}
		return isHaveSaleTicket;
	}

	/**
	 * 修改某在线班次的站点信息
	 * @param wapper 用于装载操作结果信息
	 * @param siteArray 班次模板站点集合
	 * @param classesForSale 某在线班次对象
	 */
	private void modifySiteForSaleInfo(HashMap<String, Object> wapper, JSONArray siteArray,
									   ZtcClassesForSale classesForSale) {
		List<ZtcClassesSiteForSale> sites = classesForSale.getZtcClassesSitesForSale();
		for (int k = 0; k < sites.size(); k++) {
			ZtcClassesSiteForSale site = sites.get(k);
			for (int l = 0; l < siteArray.size(); l++) {
				JSONObject siteObject = siteArray.getJSONObject(l);
				if (site.getSequence() == siteObject.getInteger("row")) {
					site.setManagerPhone(siteObject.getString("managerPhone"));
					Calendar calendar=Calendar.getInstance();
					calendar.setTime(classesForSale.getDepartureDate());
					calendar.add(Calendar.DATE,Integer.parseInt(siteObject.getString("daysAfterDepartureDate")));
					try {
						site.setDepartureTime(DATE_TIME_FORMET.parse(DATE_FORMET.format(calendar.getTime()) + " " + siteObject.getString("departureTime")));
					}catch (Exception e){
						e.printStackTrace();
					}
					String result = ztcClassesSiteForSaleManager.update(site);
					if ("0".equals(result)) {
						wapper.put("success", Boolean.valueOf(false));
						wapper.put("msg", "网络错误");
						log.info("网络错误");
						return;
					} else {
						break;
					}
				}
			}
		}
	}

	/**
	 * 删除某在线班次及其站点和价格
	 * @param wapper 用于装载操作结果信息
	 * @param classesForSale 在线班次对象
	 */
	private void deleteClassesForSaleInfo(HashMap<String, Object> wapper, ZtcClassesForSale classesForSale) {
		String deletePriceResult = ztcClassesPriceForSaleManager.delete(null, classesForSale.getId(), null);
		if ("0".equals(deletePriceResult)) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "网络错误");
			log.info("网络错误");
			return;
		}
		String deleteSiteResult = ztcClassesSiteForSaleManager.delete(null, classesForSale.getId(), null);
		if ("0".equals(deleteSiteResult)) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "网络错误");
			log.info("网络错误");
			return;
		}
		String deleteClassesresult = ztcClassesForSaleManager.delete(classesForSale.getId(),null,null,null);
		if ("0".equals(deleteClassesresult)) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "网络错误");
			log.info("网络错误");
			return;
		}
	}

	/**
	 * 修改班次模板价格对象
	 * @param id 班次模板id
	 * @param wapper 用于装载操作信息
	 * @param priceArray 班次模板价格集合
	 */
	private void modifyClassesPriceInfo(String id, HashMap<String, Object> wapper, JSONArray priceArray,User user,Date now) {
		ZtcClassesPrice ztcPrice = new ZtcClassesPrice();
		ztcPrice.setFkZtcClassesId(id);
		List<ZtcClassesPrice> classesPrices = ztcClassesPriceManager.searchInfoEquals(ztcPrice);
		for (int i = 0; i < classesPrices.size(); i++) {
			ZtcClassesPrice ztcClassesPrice = classesPrices.get(i);
			for (int j = 0; j < priceArray.size(); j++) {
				JSONObject priceObject = priceArray.getJSONObject(j);
				if (ztcClassesPrice.getId().equals(priceObject.getString("id"))) {
					ztcClassesPrice.setPrice(priceObject.getString("price"));
					ztcClassesPrice.setDistance(priceObject.getString("distance"));
					ztcClassesPrice.setModifyTime(now);
					ztcClassesPrice.setFkModifyUserId(user.getId());
					String updateResult = ztcClassesPriceManager.update(ztcClassesPrice);
					if ("0".equals(updateResult)) {
						wapper.put("success", Boolean.valueOf(false));
						wapper.put("msg", "网络错误");
						log.info("网络错误");
						return;
					}
				}
			}
		}
	}

	/**
	 * 修改班次模板站点对象
	 * @param id 班次模板id
	 * @param wapper 用于装载操作结果信息
	 * @param siteArray 班次模板站点集合
	 * @throws ParseException
	 */
	private void modifyClassesSiteInfo(String id, HashMap<String, Object> wapper, JSONArray siteArray) throws ParseException {
		ZtcClassesSite ztcSite = new ZtcClassesSite();
		ztcSite.setFkZtcClassesId(id);
		List<ZtcClassesSite> classesSites = ztcClassesSiteManager.searchInfoEquals(ztcSite);
		for (int i = 0; i < classesSites.size(); i++) {
			ZtcClassesSite classesSite = classesSites.get(i);
			for (int j = 0; j < siteArray.size(); j++) {
				JSONObject siteObject = siteArray.getJSONObject(j);
				if (classesSite.getId().equals(siteObject.getString("id"))) {
					String siteDepartureTime = siteObject.getString("departureTime");
					String daysAfterDepartureDate = siteObject.getString("daysAfterDepartureDate");
					classesSite.setManagerPhone(siteObject.getString("managerPhone"));
					classesSite.setDepartureTime(TIME_FORMET.parse(siteDepartureTime));
					classesSite.setDaysAfterDepartureDate(Integer.parseInt(daysAfterDepartureDate));
					String updateResult = ztcClassesSiteManager.update(classesSite);
					if ("0".equals(updateResult)) {
						wapper.put("success", Boolean.valueOf(false));
						wapper.put("msg", "网络错误");
						log.info("网络错误");
						return;
					}
				}
			}
		}
	}

	/**
	 * 检验站点信息是否合理
	 * @param departureDate 发车日期
	 * @param wapper 用于装载操作结果信息
	 * @param siteArray 站点对象集合
	 * @param i 当前操作的站点对象下标
	 * @param object 当前操作的站点对象
	 * @throws ParseException
	 */
	private void examineSiteInfo(String departureDate, HashMap<String, Object> wapper, JSONArray siteArray, int i,
								 JSONObject object) throws ParseException {
		String daysAfterDepartureDate = object.getString("daysAfterDepartureDate");
		String departureTime = object.getString("departureTime");
		String managerPhone = object.getString("managerPhone");
		LinkedHashMap<String, String> argumentsAndRoles = new LinkedHashMap<>();
		if ("".equals(departureTime) || departureTime == null) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "站点发车时间不可为空");
			log.info("站点发车时间不可为空");
			return;
		}
		if ("".equals(daysAfterDepartureDate) || daysAfterDepartureDate == null) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "站点与发车日期的间隔天数不可为空");
			log.info("站点与发车日期的间隔天数不可为空");
			return;
		}
		if ("".equals(managerPhone) || managerPhone == null) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "站点负责人电话不可为空");
			log.info("站点负责人电话不可为空");
			return;
		}
		argumentsAndRoles.put(daysAfterDepartureDate + "#站点与发车日期的间隔天数如'0','1'...",
				"^([0-9]{1}|[1-9][0-9]{1,})$");
		argumentsAndRoles.put(departureTime + "#站点发车时间格式如'11:11'", "^(([0][0-9])|([1][0-9])|([2][0-3])):[0-5][0-9]$");
		argumentsAndRoles.put(managerPhone + "#站点负责人电话格式如'15698965566'或'023-88965632'",
				"^(([1][0-9]{10})|([0][1-9][0-9]-[0-9]{8}))$");
		examineArgument(argumentsAndRoles, wapper);
		if ("false".equals(String.valueOf(wapper.get("success")))) {
			return;
		}
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(DATE_FORMET.parse(departureDate));
		calendar.add(Calendar.DATE,Integer.parseInt(daysAfterDepartureDate));
		String departureDateAndTime = DATE_FORMET.format(calendar.getTime())+ " " + departureTime;
		if ("0".equals(object.getString("row"))) {
			if (!daysAfterDepartureDate.equals("0")) {
				wapper.put("success", Boolean.valueOf(false));
				wapper.put("msg", "班次起始站点发车日期应与班次所设置发车日期相同");
				log.info("班次起始站点发车日期应与班次所设置发车日期相同");
				return;
			}
			Date beginTime = DATE_TIME_FORMET.parse(departureDateAndTime);
			if (beginTime.before(new Date())) {
				wapper.put("success", Boolean.valueOf(false));
				wapper.put("msg", "班次发车时间不可小于当前时间");
				log.info("班次发车时间不可小于当前时间");
				return;
			}
		}
		if (i > 0) {
			JSONObject frontObject = siteArray.getJSONObject(i - 1);
			Calendar calendarFront=Calendar.getInstance();
			calendarFront.setTime(DATE_FORMET.parse(departureDate));
			calendarFront.add(Calendar.DATE,Integer.parseInt(frontObject.getString("daysAfterDepartureDate")));
			Date frontTime = DATE_TIME_FORMET.parse(DATE_FORMET.format(calendarFront.getTime())+ " " + frontObject.getString("departureTime"));
			Date currentTime = DATE_TIME_FORMET.parse(departureDateAndTime);
			if (currentTime.getTime() <= frontTime.getTime()) {
				wapper.put("success", Boolean.valueOf(false));
				wapper.put("msg", "第" + (object.getInteger("row") + 1) + "个站点发车时间不可小于"
						+ (frontObject.getInteger("row") + 1) + "个站点发车时间");
				log.info("第" + (object.getInteger("row") + 1) + "个站点发车时间不可小于" + (frontObject.getInteger("row") + 1)
						+ "个站点发车时间");
				return;
			}
		}
	}

	/**
	 * 检验价格对象是否合理
	 * @param priceArray 价格对象集合
	 * @param wapper 用于装载操作结果信息
	 */
	private void examinePriceInfo(JSONArray priceArray, HashMap<String, Object> wapper) {
		LinkedHashMap<String, String> argumentsAndRoles = new LinkedHashMap<String, String>();
		for (int i = 0; i < priceArray.size(); i++) {
			JSONObject object = priceArray.getJSONObject(i);
			String priceString = object.getString("price");
			String distanceString = object.getString("distance");
			if (!"".equals(priceString) && priceString != null) {
				argumentsAndRoles.clear();
				if (priceString.length() > 10) {
					wapper.put("success", Boolean.valueOf(false));
					wapper.put("msg", "价格长度不可超过10位");
					log.info("价格长度不可超过10位");
					return;
				}
				argumentsAndRoles.put(priceString + "#价格的格式如'100.01'",
						"^(([1-9][0-9]{0,9})|([0-9])|(([0-9].[0-9]{1,2})|([1-9][0-9]{1,7}.[0-9]{1})|([1-9][0-9]{1,6}.[0-9]{2})))$");
				if (!"".equals(distanceString) && distanceString != null) {
					if (distanceString.length() > 8) {
						wapper.put("success", Boolean.valueOf(false));
						wapper.put("msg", "距离长度不可超过8位");
						log.info("距离长度不可超过8位");
						return;
					}
					argumentsAndRoles.put(distanceString + "#距离的格式如'100.02'",
							"^(([1-9][0-9]{0,9})|([0-9])|(([0-9].[0-9]{1,2})|([1-9][0-9]{1,7}.[0-9]{1})|([1-9][0-9]{1,6}.[0-9]{2})))$");
				}
				examineArgument(argumentsAndRoles, wapper);
			}
		}
	}

	/**
	 * 正则表达式检验参数是否合理
	 * @param arguments 参数及其正则表达式规则，相应错误提示
	 * @param wapper 用于装载操作结果信息
	 */
	private void examineArgument(HashMap<String, String> arguments, HashMap<String, Object> wapper) {
		for (String key : arguments.keySet()) {
			String[] keyCells = key.split("#");
			String[] valueCells = arguments.get(key).split("#");
			String element = keyCells[0];
			if (valueCells.length > 0) {
				for (int i = 0; i < valueCells.length; i++) {
					if (!element.matches(valueCells[i])) {
						wapper.put("success", Boolean.valueOf(false));
						wapper.put("msg", keyCells[i + 1]);
						return;
					}
				}
			}
		}
	}

	/**
	 * 根据梯形表数据生成站点集合，价格集合
	 * @param dataArray 梯形表数据集合
	 * @param siteArray 站点集合
	 * @param priceArray 价格集合
	 * @throws ParseException
	 */
	private void getSiteAndPriceArray(JSONArray dataArray, JSONArray siteArray, JSONArray priceArray)
			throws ParseException {
		siteArray.clear();
		priceArray.clear();
		if (dataArray != null) {
			for (int i = 0; i < dataArray.size(); i++) {
				JSONObject jsonObject = dataArray.getJSONObject(i);
//				String siteId = siteObject.getString("id");
//				String siteName = siteObject.getString("name");
//				String siteDetail = siteObject.getString("detailed");
//				String siteLat = siteObject.getString("lat");
//				String managerPhone = siteObject.getString("managerPhone");
//				String daysAfterDepartureDate = siteObject.getString("daysAfterDepartureDate");
//				String siteDepartureTime = siteObject.getString("departureTime");
//				String siteString = "{\"id\":\"" + siteId + "\",\"name\":\"" + siteDetail + "\",\"areaCity\":\""
//						+ siteName + "\",\"managerPhone\":\"" + managerPhone + "\",\"lat\":\"" + siteLat
//						+ "\",\"departureTime\":\"" + siteDepartureTime + "\",\"daysAfterDepartureDate\":\"" + daysAfterDepartureDate
//						+ "\",\"row\":\"" + i + "\"}";
//				siteArray.add(JSON.parseObject(siteString));
				JSONObject siteObject = new JSONObject();
				siteObject.put("id",jsonObject.getString("id"));
				siteObject.put("areaCity",jsonObject.getString("name"));
				siteObject.put("name",jsonObject.getString("detailed"));
				siteObject.put("lat",jsonObject.getString("lat"));
				siteObject.put("managerPhone",jsonObject.getString("managerPhone"));
				siteObject.put("departureTime",jsonObject.getString("departureTime"));
				siteObject.put("daysAfterDepartureDate",jsonObject.getString("daysAfterDepartureDate"));
				siteObject.put("row",i);
				siteArray.add(siteObject);

				JSONArray price = jsonObject.getJSONArray("cell");
				if (price != null) {
					for (int j = 0; j < price.size(); j++) {
						JSONObject object = price.getJSONObject(j);
						String priceValue = object.getString("pirce");
						if (!"".equals(priceValue)) {
							JSONObject priceObject = new JSONObject();
							priceObject.put("id",object.getString("id"));
							priceObject.put("price",priceValue);
							priceObject.put("distance",object.getString("distance"));
							priceObject.put("row",i);
							priceObject.put("col",j);
//							String priceId = object.getString("id");
//							String distance = object.getString("distance");
//							String priceString = "{\"id\":\"" + priceId + "\",\"price\":\"" + priceValue
//									+ "\",\"distance\":\"" + distance + "\",\"row\":\"" + i + "\",\"col\":\"" + j
//									+ "\"}";
//							JSONObject priceObject = JSON.parseObject(priceString);
							priceArray.add(priceObject);
						}
					}
				}
			}
		}
	}

	/**
	 * 根据梯形表数据，座位总数生成站点集合和价格集合
	 * @param dataArray 梯形表数据
	 * @param siteArray 用于装载站点集合
	 * @param priceArray 用于装载价格集合
	 * @param seatNumber 座位总数
	 */
	private void getSiteAndPriceWithSeatInfoArray(JSONArray dataArray, JSONArray siteArray, JSONArray priceArray,
												  String seatNumber) {
		siteArray.clear();
		priceArray.clear();
		if (dataArray != null) {
			for (int i = 0; i < dataArray.size(); i++) {
				JSONObject siteObject = dataArray.getJSONObject(i);
				String siteId = siteObject.getString("id");
				String siteName = siteObject.getString("name");
				String siteDetail = siteObject.getString("detailed");
				String siteLat = siteObject.getString("lat");
				String managerPhone = siteObject.getString("managerPhone");
				String siteDepartureTime = siteObject.getString("departureTime");
				String daysAfterDepartureDate = siteObject.getString("daysAfterDepartureDate");
				String siteString = "{\"id\":\"" + siteId + "\",\"name\":\"" + siteDetail + "\",\"areaCity\":\""
						+ siteName + "\",\"managerPhone\":\"" + managerPhone + "\",\"lat\":\"" + siteLat
						+ "\",\"departureTime\":\"" + siteDepartureTime + "\",\"daysAfterDepartureDate\":\"" + daysAfterDepartureDate  + "\",\"row\":\"" + i + "\"}";
				siteArray.add(JSON.parseObject(siteString));
				JSONArray price = siteObject.getJSONArray("cell");
				if (price != null) {
					for (int j = 0; j < price.size(); j++) {
						JSONObject object = price.getJSONObject(j);
						String priceId = object.getString("id");
						String priceValue = object.getString("pirce");
						String distance = object.getString("distance");
						if (priceValue != null && distance != null && !"".equals(priceValue) && !"".equals(distance)) {
							String seatInfo = "";
							int seatCount=Integer.parseInt(seatNumber);
							for (int k = 0; k < seatCount; k++) {
								seatInfo += "(" +(k+1) + ",0," + priceValue + ",0),";
							}
							if (seatInfo.length() > 0) {
								seatInfo = seatInfo.substring(0, seatInfo.length() - 1);
							}
							String priceString = "{\"id\":\"" + priceId + "\",\"price\":\"" + priceValue
									+ "\",\"distance\":\"" + distance + "\",\"seatInfo\":\""
									+seatInfo + "\",\"row\":\"" + i + "\",\"col\":\""
									+ j + "\"}";
							JSONObject priceObject = JSON.parseObject(priceString);
							priceArray.add(priceObject);
						}
					}
				}
			}
		}
	}

	/**
	 * 生成在线班次
	 * @param classesForSale 在线班次对象
	 * @param siteArray 班次模板站点集合
	 * @param priceArray 班次模板价格集合
	 * @param childSeatNumber 儿童座数
	 * @param seatNumber 总座数
	 * @return 操作结果信息：null.失败，非null.成功
	 * @throws ParseException
	 */
	protected String generateClassesForSale(ZtcClassesForSale classesForSale, JSONArray siteArray, JSONArray priceArray,
											String childSeatNumber,String seatNumber) throws ParseException {
		log.info("添加在售班次");
		String id = ztcClassesForSaleManager.save(classesForSale);
		if (id != null) {
			// 获取并创建站点对象
			Map<Integer, ZtcClassesSiteForSale> siteMap = new HashMap<>();
			for (int i = 0; i < siteArray.size(); i++) {
				JSONObject object = siteArray.getJSONObject(i);
				if (object == null || object.isEmpty()) {
					continue;
				}
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(classesForSale.getDepartureDate());
				calendar.add(Calendar.DATE, Integer.parseInt(object.getString("daysAfterDepartureDate")));
				ZtcClassesSiteForSale site = new ZtcClassesSiteForSale();
				String siteId = buildClassesSiteForSale(id, object,
						DATE_FORMET.format(calendar.getTime()) + " " + object.getString("departureTime"));
				if (siteId != null && !"".equals(siteId)) {
					site.setId(siteId);
					siteMap.put(object.getInteger("row"), site);
				} else {
					return null;
				}
			}
			for (int i = 0; i < priceArray.size(); i++) {
				JSONObject object = priceArray.getJSONObject(i);
				if (object == null || object.isEmpty()) {
					continue;
				}
				String priceId = buildClassesPriceForSale(id, object, siteMap, classesForSale, childSeatNumber,seatNumber);
				if (priceId == null) {
					return null;
				}
			}
		}
		return id;
	}

	/**
	 * 生成在线班次站点
	 * @param id 在线班次id
	 * @param object 包含在线班次站点信息的对象
	 * @param siteForSaleDepartureTime 站点发车时间
	 * @return 操作结果:null.失败，非null.成功
	 * @throws ParseException
	 */
	private String buildClassesSiteForSale(String id, JSONObject object, String siteForSaleDepartureTime)
			throws ParseException {
		ZtcClassesSiteForSale ztcSiteForSale = new ZtcClassesSiteForSale();
		ztcSiteForSale.setName(object.getString("name"));
		ztcSiteForSale.setManagerPhone(object.getString("managerPhone"));
		ztcSiteForSale.setAreaCity(object.getString("areaCity"));
		ztcSiteForSale.setAreaCode(object.getString("areaCode"));
		ztcSiteForSale.setLat(object.getString("lat"));
		ztcSiteForSale.setStatus(0);
		ztcSiteForSale.setType(0);
		ztcSiteForSale.setSequence(Integer.parseInt(object.getString("row")));
		ztcSiteForSale.setDepartureTime(DATE_TIME_FORMET.parse(siteForSaleDepartureTime));
		ztcSiteForSale.setFkZtcClassesForSaleId(id);
		String siteForSaleId = ztcClassesSiteForSaleManager.save(ztcSiteForSale);
		return siteForSaleId;
	}

	/**
	 *生成在线班次价格
	 * @param id 在线班次id
	 * @param object 包含价格信息的对象
	 * @param siteForSaleMap 站点及其所在行的集合
	 * @param classesForSale 在线班次对象
	 * @param childSeatNumber 儿童座数
	 * @param seatNumber 总座数
	 * @return 操作结果信息：null.失败，非null.成功
	 */
	private String buildClassesPriceForSale(String id, JSONObject object,
											Map<Integer, ZtcClassesSiteForSale> siteForSaleMap, ZtcClassesForSale classesForSale,
											String childSeatNumber,String seatNumber) {
		ZtcClassesSiteForSale start = siteForSaleMap.get(object.getInteger("col"));
		if (start == null) {
			return null;
		}
		// 设置到站点
		ZtcClassesSiteForSale end = siteForSaleMap.get(object.getInteger("row"));
		if (end == null) {
			return null;
		}
		ZtcClassesPriceForSale ztcPriceForSale = new ZtcClassesPriceForSale();
		ztcPriceForSale.setFkStartClassesSiteForSaleId(start.getId());
		ztcPriceForSale.setFkEndClassesSiteForSaleId(end.getId());
		ztcPriceForSale.setPrice(object.getString("price"));
		ztcPriceForSale.setDistance(object.getString("distance"));
		ztcPriceForSale.setStatus(0);
		ztcPriceForSale.setType(0);
		ztcPriceForSale.setRemainSeatNumber(Integer.parseInt(seatNumber));
		ztcPriceForSale.setRemainChildSeatNumber(Integer.parseInt(childSeatNumber));
		ztcPriceForSale.setSeatInfo(object.getString("seatInfo"));
		ztcPriceForSale.setFkClassesForSaleId(id);
		String priceForSaleId = ztcClassesPriceForSaleManager.save(ztcPriceForSale);
		return priceForSaleId;
	}

	/**
	 * 获取班次模板信息
	 * @param id 班次模板id
	 * @param session
	 * @return 操作结果信息
	 */
	@RequestMapping("get")
	@ResponseBody
	public HashMap<String, Object> get(String id, HttpSession session) {
		User user = (User) session.getAttribute("userInfo");
		HashMap<String, Object> wapper = new HashMap<>();
		if (user == null || "".equals(user)) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "用户未登录");
			log.info("用户未登录");
			return wapper;
		}
		ZtcClasses ztcClasses = new ZtcClasses();
		ztcClasses.setId(id);
		ZtcClasses ztcClassesBean = ztcClassesManager.searchInfoEquals(ztcClasses).get(0);
		List<ZtcClassesSite> classesSites = ztcClassesManager.getSites(ztcClassesBean);
		List<ZtcClassesPrice> classesPrices = ztcClassesManager.getPrices(ztcClassesBean);
		List<ZtcRouteAttachment> routeAttachments = ztcClassesManager.getAttachments(ztcClassesBean);
		ZtcCar car = ztcCarManager.get(ztcClassesBean.getFkZtcCarId());
		ZtcDriver driver = ztcDriverManager.get(ztcClassesBean.getFkZtcDriverId());
		String data = "[";
		List<ZtcClassesSite> startZtcClassesSites = new ArrayList<ZtcClassesSite>();
		String startName = "";
		for (int i = 0; i < classesSites.size(); i++) {
			/*if (i == 0) {
				startName = classesSites.get(i).getName();
			}*/
			ZtcClassesSite endZctClassesSite = classesSites.get(i);
			String cell = "[";
			for (int j = 0; j < startZtcClassesSites.size(); j++) {
				ZtcClassesSite startZtcClasses = startZtcClassesSites.get(j);
				if (classesPrices.size() == 0) {
					cell += "{\"pirce\":\"\",\"distance\":\"\"}";
					if (j != startZtcClassesSites.size() - 1) {
						cell += ",";
					}
				} else {
					boolean findResult = false;
					int index = 0;
					startName = classesSites.get(i).getName();
					for (int k = 0; k < classesPrices.size(); k++) {
						ZtcClassesPrice classesPrice = classesPrices.get(k);
						if (startZtcClasses.getId().equals(classesPrice.getFkStartClassesSiteId())
								&& endZctClassesSite.getId().equals(classesPrice.getFkEndClassesSiteId())) {
							index = k;
							cell += "{\"pirce\":\"" + classesPrice.getPrice() + "\",\"startName\":\"" + startName
									+ "\",\"id\":\"" + classesPrice.getId() + "\",\"distance\":\""
									+ classesPrice.getDistance() + "\"}";
							if (j != startZtcClassesSites.size() - 1) {
								cell += ",";
							}
							findResult = true;
							break;
						}
					}
					if (findResult) {
						classesPrices.remove(index);
					} else {
						cell += "{\"pirce\":\"\",\"distance\":\"\"}";
						if (j != startZtcClassesSites.size() - 1) {
							cell += ",";
						}
					}
				}
			}
			cell += "]";
			String departureTime=TIME_FORMET.format(endZctClassesSite.getDepartureTime());
			if (i == 0) {
				data += "{\"name\":\"" + (endZctClassesSite.getAreaCity() == null ? "" : endZctClassesSite.getAreaCity())
						+ "\",\"id\":\"" + endZctClassesSite.getId() + "\",\"managerPhone\":\""
						+ endZctClassesSite.getManagerPhone() + "\",\"lat\":\"" + endZctClassesSite.getLat()
						+ "\",\"row\":\"" + endZctClassesSite.getSequence() + "\",\"daysAfterDepartureDate\":\"" + endZctClassesSite.getDaysAfterDepartureDate()
						+ "\",\"departureTime\":\"" + departureTime + "\",\"remark\":\"起点\",\"detailed\":\""
						+ (endZctClassesSite.getName() == null ? "" : endZctClassesSite.getName()) + "\"}";
			} else if (i == classesSites.size() - 1) {
				data += "{\"name\":\"" + (endZctClassesSite.getAreaCity() == null ? "" : endZctClassesSite.getAreaCity())
						+ "\",\"id\":\"" + endZctClassesSite.getId() + "\",\"managerPhone\":\""
						+ endZctClassesSite.getManagerPhone() + "\",\"lat\":\"" + endZctClassesSite.getLat()
						+ "\",\"row\":\"" + endZctClassesSite.getSequence() + "\",\"daysAfterDepartureDate\":\"" + endZctClassesSite.getDaysAfterDepartureDate()
						+ "\",\"departureTime\":\"" +  departureTime + "\",\"remark\":\"终点\",\"detailed\":\""
						+ (endZctClassesSite.getName() == null ? "" : endZctClassesSite.getName()) + "\",\"cell\":" + cell
						+ "}";
			} else {
				data += "{\"name\":\"" + (endZctClassesSite.getAreaCity() == null ? "" : endZctClassesSite.getAreaCity())
						+ "\",\"id\":\"" + endZctClassesSite.getId() + "\",\"managerPhone\":\""
						+ endZctClassesSite.getManagerPhone() + "\",\"lat\":\"" + endZctClassesSite.getLat()
						+ "\",\"row\":\"" + endZctClassesSite.getSequence() + "\",\"daysAfterDepartureDate\":\"" + endZctClassesSite.getDaysAfterDepartureDate()
						+ "\",\"departureTime\":\"" +  departureTime+ "\",\"detailed\":\""
						+ (endZctClassesSite.getName() == null ? "" : endZctClassesSite.getName()) + "\",\"cell\":" + cell
						+ "}";
			}
			startZtcClassesSites.add(endZctClassesSite);
		}
		data += "]";
		int groupIndex = 0;
		int groupNumber = 0;
		if (routeAttachments.size() > 0) {
			groupNumber = routeAttachments.get(0).getGroupNumber();
		}
		int count = 0;
		String attachmentValue = "[";
		while (true) {
			String attachmentElement = "{\"group\":[";
			for (int i = groupIndex; i < routeAttachments.size(); i++) {
				ZtcRouteAttachment routeAttachment = routeAttachments.get(i);
				if (routeAttachment.getGroupNumber() != groupNumber) {
					groupIndex = i;
					groupNumber = routeAttachment.getGroupNumber();
					break;
				}
				if (routeAttachment.getFkAttachmentId() == null || "".equals(routeAttachment.getFkAttachmentId())) {
					attachmentElement += "{\"img\":\"\",\"text\":\"" + routeAttachment.getViewContent() + "\"}";
				} else {
					Attachment attachment = routeAttachment.getAttachment();
					byte[] fileBody=attachment.getFileBody();
					for (int j = 0; j < fileBody.length; ++j) {
						if (fileBody[j] > 0) {
							// 调整异常数据
							fileBody[j] -= 256;
						}
					}
					String bodyInfo = new BASE64Encoder().encode(fileBody);
					attachmentElement += "{\"img\":\"data:" + attachment.getFileType() + ";base64,"
							+ bodyInfo + "\",\"text\":\""
							+ routeAttachment.getViewContent() + "\"}";
				}
				count++;
			}
			if (count == routeAttachments.size()) {
				attachmentElement += "]}";
				attachmentValue += attachmentElement;
				break;
			} else {
				attachmentElement += "]},";
				attachmentValue += attachmentElement;
			}
		}
		attachmentValue += "]";
		ZtcClassesForSale ztcClassesForSale = new ZtcClassesForSale();
		ztcClassesForSale.setFkZtcClassesId(ztcClassesBean.getId());
		List<ZtcClassesForSale> ztcClassesForSaleList = ztcClassesForSaleManager.searchInfoEqualsNoSort(ztcClassesForSale);
		if (ztcClassesBean.getDepartureType() == 1) {
			//String selectDates = "[";
			JSONArray jsonArray = new JSONArray();
			for (int i = 0; i < ztcClassesForSaleList.size(); i++) {
				//selectDates+="\""+DATE_FORMET.format(ztcClassesForSaleList.get(i).getDepartureDate())+
				jsonArray.add(DATE_FORMET.format(ztcClassesForSaleList.get(i).getDepartureDate()));
			}
			wapper.put("selectDates", JSON.toJSONString(jsonArray));
		} else {
			ZtcClassesForSale lastClassesForSale = ztcClassesForSaleList.get(ztcClassesForSaleList.size() - 1);
			Date illegalStartDate = new Date();
			Date illegalEndDate = lastClassesForSale.getDepartureDate();
			Calendar calendar = Calendar.getInstance();
			wapper.put("illegalStartDate", DATE_FORMET.format(illegalStartDate));
			if (illegalEndDate.getTime() > illegalStartDate.getTime()) {
				calendar.setTime(illegalEndDate);
				calendar.add(Calendar.DATE, 2);
				illegalEndDate = calendar.getTime();
				wapper.put("illegalEndDate", DATE_FORMET.format(illegalEndDate));
			} else {
				calendar.set(9999, 12, 31);
				illegalEndDate = calendar.getTime();
				wapper.put("illegalEndDate", DATE_FORMET.format(illegalEndDate));
			}
		}
		wapper.put("success", Boolean.valueOf(true));
		wapper.put("id", id);
		wapper.put("carType", ztcClassesBean.getCarType());
		wapper.put("name", ztcClassesBean.getName());
		wapper.put("remark", ztcClassesBean.getRemark());
		wapper.put("data", JSON.parseArray(data));
		wapper.put("attachment", JSON.parseArray(attachmentValue));
		wapper.put("car", car);
		wapper.put("driver", driver);
		wapper.put("seatNumber", ztcClassesBean.getSeatNumber());
		wapper.put("childSeatNumber", ztcClassesBean.getChildSeatNumber());
		wapper.put("isRefund", ztcClassesBean.getIsRefund());
		wapper.put("departureType", ztcClassesBean.getDepartureType() + 1);
		wapper.put("dayFrequencyType", ztcClassesBean.getDayFrequenceType());
		if(ztcClassesBean.getWeekAllDays()!=null){
			String[] weekDays=ztcClassesBean.getWeekAllDays().split(",");
			JSONArray jsonArray = new JSONArray();
			for(int i=0;i<weekDays.length;i++){
				jsonArray.add(weekDays[i]);
			}
			wapper.put("weekAllDays", JSON.toJSONString(jsonArray));
		}
		if(ztcClassesBean.getMonthAllDays()!=null){
			String[] monthDays=ztcClassesBean.getMonthAllDays().split(",");
			JSONArray jsonArrayTwo = new JSONArray();
			for(int i=0;i<monthDays.length;i++){
				jsonArrayTwo.add(monthDays[i]);
			}
			wapper.put("monthAllDays", JSON.toJSONString(jsonArrayTwo));
		}
		wapper.put("departureDate", ztcClassesBean.getDepartureDate());
		wapper.put("preSaleDays", ztcClassesBean.getPreSaleDays());
		wapper.put("remark", ztcClassesBean.getRemark());
		wapper.put("forbidSaleTimeRegionBeforeDeparture", ztcClassesBean.getForbidSaleTimeRegionBeforeDeparture());
		return wapper;
	}

	/**
	 * 获取班次模板的自动排班截止日期
	 * @param id 班次模板id
	 * @param session
	 * @return 操作结果信息
	 */
	@RequestMapping("getToUpdateAutoArrangeEndDate")
	@ResponseBody
	public HashMap<String, Object> getToUpdateAutoArrangeEndDate(String id, HttpSession session) {
		User user = (User) session.getAttribute("userInfo");
		HashMap<String, Object> wapper = new HashMap<>();
		if (user == null || "".equals(user)) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "用户未登录");
			log.info("用户未登录");
			return wapper;
		}
		ZtcClasses ztcClasses = new ZtcClasses();
		ztcClasses.setId(id);
		ZtcClasses ztcClassesBean = ztcClassesManager.searchInfoEquals(ztcClasses).get(0);
		if (ztcClassesBean.getDepartureType() == 0) {
			ZtcClassesForSale ztcClassesForSale = new ZtcClassesForSale();
			ztcClassesForSale.setFkZtcClassesId(ztcClassesBean.getId());
			List<ZtcClassesForSale> ztcClassesForSaleList = ztcClassesForSaleManager.searchInfoEqualsNoSort(ztcClassesForSale);
			ZtcClassesForSale lastClassesForSale = ztcClassesForSaleList.get(ztcClassesForSaleList.size() - 1);
			wapper.put("lastClassesForSaleDate", DATE_FORMET.format(lastClassesForSale.getDepartureDate()));
		}
		wapper.put("success", Boolean.valueOf(true));
		wapper.put("id", id);
		wapper.put("autoArrangeEndDate", ztcClassesBean.getAutoArrangeEndDate());
		return wapper;
	}
	/**
	 * 修改班次模板自动排班截止日期
	 * @param id 班次模板id
	 * @param autoArrangeEndDate 自动排班截止日期
	 * @param session
	 * @return 操作结果信息
	 * @throws ParseException 字符串转日期出错
	 */
	@RequestMapping("updateAutoArrangeEndDate")
	@ResponseBody
	public HashMap<String, Object> updateAutoArrangeEndDate(String id, String autoArrangeEndDate, HttpSession session) throws ParseException {
		Date now = new Date();
		HashMap<String, Object> wapper = new HashMap<>();
		User user = (User) session.getAttribute("userInfo");
		if (user == null || "".equals(user)) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "用户未登录");
			log.info("用户未登录");
			return wapper;
		}
		ZtcTransport transport = ztcTransportManager.get(user.getTransportId());
		int transportType = transport.getType();
		if (transportType == 0 || transportType == 1 || transportType == 2) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "非运营公司或车方不可操作班次");
			log.info("非运营公司或车方不可操作班次");
			return wapper;
		}
		if (transport.getStatus() == 4) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "该用户公司已被冻结，不可修改班次");
			log.info("该用户公司已被冻结，不可修改班次");
			return wapper;
		}
		if (!"".equals(autoArrangeEndDate) && autoArrangeEndDate != null&&autoArrangeEndDate.matches("^[2][0-9]{3}-(([0][1-9])|([1][0-2]))-(([1-2][0-9])|([0][1-9])|([3][0-1]))$")) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "停止排班日期格式如'2017-12-26'必须大于等于班次模板的最后排班日期");
			return wapper;
		}
		ZtcClasses ztcClasses = new ZtcClasses();
		ztcClasses.setId(id);
		ZtcClasses ztcClassesBean = ztcClassesManager.searchInfoEquals(ztcClasses).get(0);
		if (ztcClassesBean.getTicketStatus() == 1) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "该班次已停售");
			log.info("该班次已停售");
			return wapper;
		}
		ztcClassesBean.setModifyTime(now);
		ztcClassesBean.setFkModifyUserId(user == null ? "" : user.getId());
		ztcClassesBean.setAutoArrangeEndDate(DATE_FORMET.parse(autoArrangeEndDate));
		String ztcClassesBeanId = ztcClassesManager.update(ztcClassesBean);
		if ("0".equals(ztcClassesBeanId)) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "网络错误");
			log.info("网络错误");
			return wapper;
		}
		wapper.put("success", Boolean.valueOf(true));
		wapper.put("data", "修改成功");
		log.info("修改成功");
		return wapper;
	}

	/**
	 * 获取班次模板可统一修改的部分信息，包括车型，车，司机，停售时间，预售期，是否可退票，总座数，儿童座
	 * @param id 班次模板id
	 * @param session
	 * @return 操作结果信息
	 *//*
	@RequestMapping("getToUpdateSomeInfo")
	@ResponseBody
	public HashMap<String, Object> getToUpdateSomeInfo(String id, HttpSession session) {
		User user = (User) session.getAttribute("userInfo");
		HashMap<String, Object> wapper = new HashMap<>();
		if (user == null || "".equals(user)) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "用户未登录");
			log.info("用户未登录");
			return wapper;
		}
		ZtcClasses ztcClasses = new ZtcClasses();
		ztcClasses.setId(id);
		ZtcClasses ztcClassesBean = ztcClassesManager.searchInfoEquals(ztcClasses).get(0);
		ZtcCar car = ztcCarManager.get(ztcClassesBean.getFkZtcCarId());
		ZtcDriver driver = ztcDriverManager.get(ztcClassesBean.getFkZtcDriverId());
		wapper.put("success", Boolean.valueOf(true));
		wapper.put("id", id);
		wapper.put("carType", ztcClassesBean.getCarType());
		wapper.put("car", car);
		wapper.put("driver", driver);
		wapper.put("seatNumber", ztcClassesBean.getSeatNumber());
		wapper.put("childSeatNumber", ztcClassesBean.getChildSeatNumber());
		wapper.put("isRefund", ztcClassesBean.getIsRefund());
		wapper.put("preSaleDays", ztcClassesBean.getPreSaleDays());
		wapper.put("forbidSaleTimeRegionBeforeDeparture", ztcClassesBean.getForbidSaleTimeRegionBeforeDeparture());
		return wapper;
	}

	*//**
	 * 修改班次模板及其当前日期之后所有在线班次的部分信息
	 * @param id 在线班次模板id
	 * @param carType 车型
	 * @param carId 车辆id
	 * @param driverId 司机id
	 * @param seatNumber 总座位数
	 * @param childSeatNumber 儿童座位数
	 * @param isRefund 是否可退票：true，是；false，否
	 * @param fsTimerbDeparture 开车前多长时间停止售票
	 * @param preSaleDays 预售天数
	 * @param session
	 * @return 操作结果信息
	 * @throws ParseException 字符串转日期出错
	 *//*
	@RequestMapping("updateSomeInfo")
	@ResponseBody
	public HashMap<String, Object> updateSomeInfo(String id, String carType, String carId, String driverId, String seatNumber,
												  String childSeatNumber, String isRefund, String fsTimerbDeparture,String preSaleDays, HttpSession session) throws ParseException {
		Date now = new Date();
		HashMap<String, Object> wapper = new HashMap<>();
		User user = (User) session.getAttribute("userInfo");
		if (user == null || "".equals(user)) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "用户未登录");
			log.info("用户未登录");
			return wapper;
		}
		ZtcTransport transport = ztcTransportManager.get(user.getTransportId());
		int transportType = transport.getType();
		if (transportType == 0 || transportType == 1 || transportType == 2) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "非运营公司或车方不可操作班次");
			log.info("非运营公司或车方不可操作班次");
			return wapper;
		}
		if (transport.getStatus() == 4) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "该用户公司已被冻结，不可修改班次");
			log.info("该用户公司已被冻结，不可修改班次");
			return wapper;
		}
		LinkedHashMap<String, String> argumentsAndRoles = new LinkedHashMap<>();
		if ("".equals(carId) || carId == null) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "请选择车辆");
			return wapper;
		}
		if ("".equals(driverId) || driverId == null) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "请选择司机");
			return wapper;
		}
		if ("".equals(fsTimerbDeparture) || fsTimerbDeparture == null) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "请填写发车前暂停售票的时间范围");
			return wapper;
		}
		argumentsAndRoles.put(fsTimerbDeparture + "#发车前暂停售票的时间范围格式如'1.01'",
				"^(([1-9][0-9]{0,9})|([0])|(([0-9].[0-9]{1,2})|([1-9][0-9]{1,7}.[0-9]{1})|([1-9][0-9]{1,6}.[0-9]{2})))$");
		if ("".equals(seatNumber) || seatNumber == null) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "请填写总座数");
			return wapper;
		}
		argumentsAndRoles.put(seatNumber + "#总票格式如'9'或'12'最小为1最大不超过65", "^(([1-9])|([1-5][0-9])|([6][0-5]))$");
		if ("".equals(childSeatNumber) || childSeatNumber == null) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "请填写儿童座数");
			return wapper;
		}
		argumentsAndRoles.put(childSeatNumber + "#儿童票格式如'0'最大不超过6", "^[0-6]$");
		if ("".equals(preSaleDays) || preSaleDays == null) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "请填写预售期");
			return wapper;
		}
		argumentsAndRoles.put(preSaleDays + "#预售期格式如'1'必须大于等于1", "^(([1-9])|([1-9][0-9]+))$");
		examineArgument(argumentsAndRoles, wapper);
		if ("false".equals(String.valueOf(wapper.get("success")))) {
			return wapper;
		}
		// 修改魔板班次
		ZtcClasses ztcClasses = new ZtcClasses();
		ztcClasses.setId(id);
		ZtcClasses ztcClassesBean = ztcClassesManager.searchInfoEquals(ztcClasses).get(0);
		if (ztcClassesBean.getTicketStatus() == 1) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "该班次已停售");
			log.info("该班次已停售");
			return wapper;
		}
		ztcClassesBean.setModifyTime(now);
		ztcClassesBean.setFkModifyUserId(user == null ? "" : user.getId());
		ztcClassesBean.setCarType(Integer.parseInt(carType));
		ztcClassesBean.setFkZtcCarId(carId);
		ztcClassesBean.setFkZtcDriverId(driverId);
		ztcClassesBean.setIsRefund("true".equals(isRefund) ? 1 : 0);
		ztcClassesBean.setPreSaleDays(Integer.parseInt(preSaleDays));
		int intSeatNumber = Integer.parseInt(seatNumber);
		int intChildSeatNumber = Integer.parseInt(childSeatNumber);
		if (intChildSeatNumber > (int) (intSeatNumber * childSeatRatio)) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "儿童票不能高于成人票的10%");
			log.info("儿童票不能高于成人票的10%");
			return wapper;
		}
		ztcClassesBean.setSeatNumber(intSeatNumber);
		ztcClassesBean.setChildSeatNumber(intChildSeatNumber);
		ztcClassesBean.setForbidSaleTimeRegionBeforeDeparture(fsTimerbDeparture);
		String ztcClassesBeanId = ztcClassesManager.update(ztcClassesBean);
		if ("0".equals(ztcClassesBeanId)) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "网络错误");
			log.info("网络错误");
			return wapper;
		}
		ZtcClassesForSale ztcClassesForSale = new ZtcClassesForSale();
		ztcClassesForSale.setFkZtcClassesId(id);
		List<ZtcClassesForSale> ztcClassesForSales = ztcClassesForSaleManager.searchInfoWithDate(ztcClassesForSale,
				DATE_FORMET.format(new Date()), null);
		// 修改在售班次价格信息
		for (int i= 0; i < ztcClassesForSales.size(); i++) {
			ZtcClassesForSale classesForSale = ztcClassesForSales.get(i);
			ZtcClassesPriceForSale price = new ZtcClassesPriceForSale();
			price.setFkClassesForSaleId(classesForSale.getId());
			List<ZtcClassesPriceForSale> prices = ztcClassesPriceForSaleManager.searchInfoEquals(price);
			int stopPriceCount = 0;
			int onPriceCount = 0;
			for (int j = 0; j < prices.size(); j++) {
				// 需要修改价格和距离
				ZtcClassesPriceForSale priceForSale = prices.get(j);
				ZtcOrder ztcOrder = new ZtcOrder();
				ztcOrder.setFkZtcClassesPriceForSaleId(priceForSale.getId());
				int saleChildSeatNumber = 0;
				List<ZtcOrder> orders = orderManager.searchInfo(ztcOrder);
				List<ZtcOrderTicket> orderTickets = new ArrayList<ZtcOrderTicket>();
				if (orders != null && orders.size() > 0) {
					for (int k = 0; k < orders.size(); k++) {
						ZtcOrder order = orders.get(k);
						ZtcOrderTicket ticket = new ZtcOrderTicket();
						ticket.setFkOrderId(order.getId());
						ticket.setStatus(0);
						orderTickets.addAll(orderTicketManager.searchInfoEquals(ticket));
					}
				}
				if (orderTickets.size() > 0) {
					for (int k = 0; k < orderTickets.size(); k++) {
						ZtcOrderTicket ticket = orderTickets.get(k);
						if (ticket.getSeatType() == 3) {
							saleChildSeatNumber++;
						}
					}
				}
				String seatInfo = priceForSale.getSeatInfo();
				String[] seatInfos = seatInfo.split("\\u0029,");
				int[] seatNumbers = new int[seatInfos.length];
				for (int k = 0; k < seatInfos.length; k++) {
					String seat = seatInfos[k];
					if ("".equals(seat)) {
						continue;
					}
					int seatIndex = seat.indexOf(")");
					if (seatIndex > 0) {
						seat = seat.substring(1, seatIndex);
					} else {
						seat = seat.substring(1);
					}
					String[] tags = seat.split(",");
					seatNumbers[k] = Integer.parseInt(tags[0]);
				}
				Arrays.sort(seatNumbers);
				if (Integer.parseInt(seatNumber) < seatNumbers.length) {
					// 减少总座位数，删掉多余座位信息，重设儿童座位数
					stopPriceCount = subClassesPriceForSaleSeatInfo(seatNumber, childSeatNumber, priceForSale,
							saleChildSeatNumber, seatInfos, seatNumbers);
				} else {
					// 添加总座位数,添加少的座位信息，重设儿童座位数
					onPriceCount = addClassesPriceForSaleSeatInfo(seatNumber, childSeatNumber, priceForSale,
							saleChildSeatNumber, seatInfos, seatNumbers);
				}
				ztcClassesPriceForSaleManager.update(priceForSale);
			}
			classesForSale.setCarType(Integer.parseInt(carType));
			classesForSale.setFkZtcCarId(carId);
			classesForSale.setFkZtcDriverId(driverId);
			classesForSale.setIsRefund("true".equals(isRefund) ? 1 : 0);
			classesForSale.setForbidSaleTimeRegionBeforeDeparture(fsTimerbDeparture);
			classesForSale.setChildSeatNumber(Integer.parseInt(childSeatNumber));
			classesForSale.setSeatNumber(Integer.parseInt(seatNumber));
			classesForSale.setModifyTime(now);
			classesForSale.setFkModifyUserId(user == null ? "" : user.getId());
			if (stopPriceCount == prices.size()) {
				classesForSale.setTicketStatus(1);
			} else {
				if (onPriceCount > 0) {
					classesForSale.setTicketStatus(0);
				}
			}
			String result = ztcClassesForSaleManager.update(classesForSale);
			if ("0".equals(result)) {
				wapper.put("success", Boolean.valueOf(false));
				wapper.put("msg", "网络错误");
				log.info("网络错误");
				return wapper;
			}
		}
		wapper.put("success", Boolean.valueOf(true));
		wapper.put("data", "修改成功");
		log.info("修改成功");
		return wapper;
	}*/
	/**
	 * 根据页数，名称获取班次列表，并生成可供页面展示的数据信息
	 * @param pageNumber 页数
	 * @param name 名称
	 * @param session
	 * @return 可供页面展示的数据信息，总条数，页数，名称
	 */
	@RequestMapping("getList")
	@ResponseBody
	public HashMap<String, Object> getList(String pageNumber, String name, HttpSession session) {
		User user = (User) session.getAttribute("userInfo");
		HashMap<String, Object> wapper = new HashMap<>();
		if (user == null || "".equals(user)) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "用户未登录");
			log.info("用户未登录");
			return wapper;
		}
		LinkedHashMap<String, String> argumentsAndRoles = new LinkedHashMap<>();
		if (pageNumber != null) {
			argumentsAndRoles.put(pageNumber + "#页数必须为数字", "^(([0-9])|([1-9][0-9]{0,}))$");
			examineArgument(argumentsAndRoles, wapper);
			if ("false".equals(String.valueOf(wapper.get("success")))) {
				return wapper;
			}
		}
		ZtcTransport transport = ztcTransportManager.get(user.getTransportId());
		ZtcClasses classes = new ZtcClasses();
		classes.setName(name);
		classes.setFkTransportId(user.getTransportId());
		List<ZtcClasses> list = ztcClassesManager.searchInfoLikes(classes, String.valueOf(transport.getType()),
				pageNumber);
		String stringList = "[";
		for (int i = 0; i < list.size(); i++) {
			ZtcClasses ztcClasses = list.get(i);
			String carNumber = "随机";
			if (ztcClasses.getFkZtcCarId() != null && !"随机".equals(ztcClasses.getFkZtcCarId())) {
				ZtcCar car = ztcCarManager.get(ztcClasses.getFkZtcCarId());
				carNumber = car.getCarNumber();
			}
			String element = "{\"name\":\"" + ztcClasses.getName() + "\",\"remark\":\"" + ztcClasses.getRemark()
					+ "\",\"addTime\":\"" + ztcClasses.getAddTime() + "\",\"ticketStatus\":\""
					+ ztcClasses.getTicketStatus() + "\",\"carNumber\":\"" + carNumber + "\",\"carId\":\""
					+ ((ztcClasses.getFkZtcCarId() == null || "随机".equals(ztcClasses.getFkZtcCarId())) ? "随机"
					: ztcClasses.getFkZtcCarId());
			List<ZtcClassesSite> sites = ztcClassesManager.getSites(ztcClasses);
			ZtcClassesSite startSite = sites.get(0);
			ZtcClassesSite endSite = sites.get(sites.size() - 1);
			element += "\",\"startSiteName\":\"" + startSite.getAreaCity() + "\",\"startSiteAreaCity\":\""
					+ startSite.getName() + "\",\"startSiteManagerPhone\":\"" + startSite.getManagerPhone()
					+ "\",\"startSiteLat\":\"" + startSite.getLat() + "\",\"endSiteName\":\"" + endSite.getAreaCity()
					+ "\",\"endSiteAreaCity\":\"" + endSite.getName() + "\",\"endSiteManagerPhone\":\""
					+ endSite.getManagerPhone() + "\",\"endSiteLat\":\"" + endSite.getLat();
			element += "\",\"id\":\"" + ztcClasses.getId();
			element += "\",\"cell\":[";
			for (int j = 0; j < sites.size(); j++) {
				ZtcClassesSite classesSite = sites.get(j);
				String departureTime=TIME_FORMET.format(classesSite.getDepartureTime());
				if (j == 0) {
					element += "{\"name\":\"" + classesSite.getAreaCity() + "\",\"remark\":\"起点\",\"sequence\":\""
							+ classesSite.getSequence() + "\",\"areaCity\":\"" + classesSite.getName()
							+ "\",\"managerPhone\":\"" + classesSite.getManagerPhone() + "\",\"row\":\""
							+ classesSite.getSequence() + "\",\"id\":\"" + classesSite.getId() + "\",\"areaCode\":\""
							+ classesSite.getAreaCode() + "\",\"lat\":\"" + classesSite.getLat()
							+ "\",\"daysAfterDepartureDate\":\"" + classesSite.getDaysAfterDepartureDate()+ "\",\"departureTime\":\"" + departureTime + "\"},";
				} else if (j == sites.size() - 1) {
					element += "{\"name\":\"" + classesSite.getAreaCity() + "\",\"remark\":\"终点\",\"sequence\":\""
							+ classesSite.getSequence() + "\",\"areaCity\":\"" + classesSite.getName()
							+ "\",\"managerPhone\":\"" + classesSite.getManagerPhone() + "\",\"row\":\""
							+ classesSite.getSequence() + "\",\"id\":\"" + classesSite.getId() + "\",\"areaCode\":\""
							+ classesSite.getAreaCode() + "\",\"lat\":\"" + classesSite.getLat()
							+ "\",\"daysAfterDepartureDate\":\"" + classesSite.getDaysAfterDepartureDate()+ "\",\"departureTime\":\"" + departureTime + "\"}";
				} else {
					element += "{\"name\":\"" + classesSite.getAreaCity() + "\",\"sequence\":\""
							+ classesSite.getSequence() + "\",\"id\":\"" + classesSite.getId() + "\",\"areaCity\":\""
							+ classesSite.getName() + "\",\"managerPhone\":\"" + classesSite.getManagerPhone()
							+ "\",\"row\":\"" + classesSite.getSequence() + "\",\"areaCode\":\""
							+ classesSite.getAreaCode() + "\",\"lat\":\"" + classesSite.getLat()
							+ "\",\"daysAfterDepartureDate\":\"" + classesSite.getDaysAfterDepartureDate()+ "\",\"departureTime\":\"" + departureTime + "\"},";
				}
			}
			element += "]}";
			stringList += element;
			if (i != list.size() - 1) {
				stringList += ",";
			}
		}
		stringList += "]";
		JSONArray jsonList = JSON.parseArray(stringList);
		wapper.put("list", jsonList);
		wapper.put("success", Boolean.valueOf(true));
		wapper.put("listSize",
				ztcClassesManager.getCount(name, String.valueOf(transport.getType()), user.getTransportId()));
		wapper.put("name", name);
		wapper.put("pageNumber", pageNumber);
		return wapper;
	}

	/**
	 * 停售班次模板及停售从开始日期起所有的在线班次
	 * @param id 班次模板id
	 * @param stopBeginDate 开始日期
	 * @param session
	 * @return 操作结果信息
	 * @throws ParseException
	 *//*
	@RequestMapping("stopSell")
	@ResponseBody
	public HashMap<String, Object> stopSell(String id,String stopBeginDate, HttpSession session) throws ParseException{
		Date now = new Date();
		HashMap<String, Object> wapper = new HashMap<>();
		User user = (User) session.getAttribute("userInfo");
		if (user == null || "".equals(user)) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "用户未登录");
			log.info("用户未登录");
			return wapper;
		}
		ZtcTransport transport = ztcTransportManager.get(user.getTransportId());
		int transportType = transport.getType();
		if (transportType == 0 || transportType == 1 || transportType == 2) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "非运营公司或车方不可操作班次");
			log.info("非运营公司或车方不可操作班次");
			return wapper;
		}
		if (transport.getStatus() == 4) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "该用户公司已被冻结，不可停售班次");
			log.info("该用户公司已被冻结，不可停售班次");
			return wapper;
		}
		if(stopBeginDate==null||"".equals(stopBeginDate)){
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "停售开始日期不可为空");
			log.info("停售开始日期不可为空");
			return wapper;
		}
		if(!stopBeginDate.matches("^[2][0-9]{3}-(([0][1-9])|([1][0-2]))-(([1-2][0-9])|([0][1-9])|([3][0-1]))$")) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "停售开始日期格式如'2017-12-26'");
			log.info("停售开始日期格式如'2017-12-26'");
			return wapper;
		}
		Date stopStartDate=DATE_FORMET.parse(stopBeginDate);
		if(stopStartDate.getTime()<now.getTime()){
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "停售开始日期必须大于等于当前日期");
			log.info("停售开始日期必须大于等于当前日期");
			return wapper;
		}
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(now);
		calendar.add(Calendar.DATE,35);
		Date endillegalDate=calendar.getTime();
		if(stopStartDate.getTime()>endillegalDate.getTime()){
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "停售开始日期必须小于等于当前日期之后的35天");
			log.info("停售开始日期必须小于等于当前日期之后的35天");
			return wapper;
		}
		ZtcClasses ztcClasses = new ZtcClasses();
		ztcClasses.setId(id);
		ZtcClasses ztcClassesBean = ztcClassesManager.searchInfoEquals(ztcClasses).get(0);
		ZtcClassesForSale ztcClassesForSale = new ZtcClassesForSale();
		ztcClassesForSale.setFkZtcClassesId(ztcClassesBean.getId());
		ztcClassesForSale.setTicketStatus(0);
		List<ZtcClassesForSale> ztcClassesForSales = ztcClassesForSaleManager.searchInfoWithDateNoSort(ztcClassesForSale,stopBeginDate,null);
		for (int i = 0; i < ztcClassesForSales.size(); i++) {
			ZtcClassesForSale element = ztcClassesForSales.get(i);
			element.setFkModifyUserId(user == null ? "" : user.getId());
			element.setModifyTime(now);
			String result = ztcClassesForSaleManager.stopSell(element);
			if ("0".equals(result)) {
				wapper.put("success", Boolean.valueOf(false));
				wapper.put("msg", "操作失败");
				return wapper;
			}
		}
		ztcClassesBean.setFkModifyUserId(user == null ? "" : user.getId());
		ztcClassesBean.setModifyTime(now);
		ztcClassesBean.setTicketStatus(1);
		String updateResult = ztcClassesManager.update(ztcClassesBean);
		if ("0".equals(updateResult)) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "停售失败");
			return wapper;
		}
		wapper.put("success", Boolean.valueOf(true));
		wapper.put("data", "停售成功");
		return wapper;
	}*/
	/**
	 * 停售班次模板及其所有的在线班次
	 * @param id 班次模板id
	 * @param session
	 * @return 操作结果信息
	 * @throws ParseException
	 */
	@RequestMapping("stopSell")
	@ResponseBody
	public HashMap<String, Object> stopSell(String id, HttpSession session) throws ParseException{
		Date now = new Date();
		HashMap<String, Object> wapper = new HashMap<>();
		User user = (User) session.getAttribute("userInfo");
		if (user == null || "".equals(user)) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "用户未登录");
			log.info("用户未登录");
			return wapper;
		}
		ZtcTransport transport = ztcTransportManager.get(user.getTransportId());
		int transportType = transport.getType();
		if (transportType == 0 || transportType == 1 || transportType == 2) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "非运营公司或车方不可操作班次");
			log.info("非运营公司或车方不可操作班次");
			return wapper;
		}
		if (transport.getStatus() == 4) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "该用户公司已被冻结，不可停售班次");
			log.info("该用户公司已被冻结，不可停售班次");
			return wapper;
		}
		ZtcClasses ztcClasses = new ZtcClasses();
		ztcClasses.setId(id);
		ZtcClasses ztcClassesBean = ztcClassesManager.searchInfoEquals(ztcClasses).get(0);
		ZtcClassesForSale ztcClassesForSale = new ZtcClassesForSale();
		ztcClassesForSale.setFkZtcClassesId(ztcClassesBean.getId());
		ztcClassesForSale.setTicketStatus(0);
		List<ZtcClassesForSale> ztcClassesForSales = ztcClassesForSaleManager.searchInfoWithDateNoSort(ztcClassesForSale,null,null);
		for (int i = 0; i < ztcClassesForSales.size(); i++) {
			ZtcClassesForSale element = ztcClassesForSales.get(i);
			element.setFkModifyUserId(user == null ? "" : user.getId());
			element.setModifyTime(now);
			String result = ztcClassesForSaleManager.stopSell(element,user,now);
			if ("0".equals(result)) {
				wapper.put("success", Boolean.valueOf(false));
				wapper.put("msg", "停售失败");
				return wapper;
			}
		}
		ztcClassesBean.setFkModifyUserId(user == null ? "" : user.getId());
		ztcClassesBean.setModifyTime(now);
		ztcClassesBean.setTicketStatus(1);
		String updateResult = ztcClassesManager.update(ztcClassesBean);
		if ("0".equals(updateResult)) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "停售失败");
			return wapper;
		}
		wapper.put("success", Boolean.valueOf(true));
		wapper.put("data", "停售成功");
		return wapper;
	}

	/**
	 * 起售班次模板及其所有的停售班次
	 * @param id 班次模板id
	 * @param session
	 * @return 操作结果信息
	 */
	@RequestMapping("restartToSell")
	@ResponseBody
	public HashMap<String,Object> restartToSell(String id,HttpSession session){
		Date now = new Date();
		HashMap<String, Object> wapper = new HashMap<>();
		User user = (User) session.getAttribute("userInfo");
		if (user == null || "".equals(user)) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "用户未登录");
			log.info("用户未登录");
			return wapper;
		}
		ZtcTransport transport = ztcTransportManager.get(user.getTransportId());
		int transportType = transport.getType();
		if (transportType == 0 || transportType == 1 || transportType == 2) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "非运营公司或车方不可操作班次");
			log.info("非运营公司或车方不可操作班次");
			return wapper;
		}
		if (transport.getStatus() == 4) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "该用户公司已被冻结，不可停售班次");
			log.info("该用户公司已被冻结，不可停售班次");
			return wapper;
		}
		ZtcClasses ztcClasses = new ZtcClasses();
		ztcClasses.setId(id);
		ZtcClasses ztcClassesBean = ztcClassesManager.searchInfoEquals(ztcClasses).get(0);
		ZtcClassesForSale ztcClassesForSale = new ZtcClassesForSale();
		ztcClassesForSale.setFkZtcClassesId(ztcClassesBean.getId());
		ztcClassesForSale.setTicketStatus(1);
		List<ZtcClassesForSale> ztcClassesForSales = ztcClassesForSaleManager.searchInfoWithDateNoSort(ztcClassesForSale,null,null);
		for (int i = 0; i < ztcClassesForSales.size(); i++) {
			ZtcClassesForSale element = ztcClassesForSales.get(i);
			element.setFkModifyUserId(user == null ? "" : user.getId());
			element.setModifyTime(now);
			String result = ztcClassesForSaleManager.restartToSell(element,user,now);
			if ("0".equals(result)) {
				wapper.put("success", Boolean.valueOf(false));
				wapper.put("msg", "起售失败");
				return wapper;
			}
		}
		ztcClassesBean.setFkModifyUserId(user == null ? "" : user.getId());
		ztcClassesBean.setModifyTime(now);
		ztcClassesBean.setTicketStatus(0);
		String updateResult = ztcClassesManager.update(ztcClassesBean);
		if ("0".equals(updateResult)) {
			wapper.put("success", Boolean.valueOf(false));
			wapper.put("msg", "起售失败");
			return wapper;
		}
		wapper.put("success", Boolean.valueOf(true));
		wapper.put("data", "起售成功");
		return wapper;
	}
}